列表中有一个 属性 的 c# 映射器对象
c# mapper object with one property from list
我有一个引擎名称、引擎马力和列表 carid 的请求。我怎样才能将 EngineTMP 映射到 EngineModelDto?
Table engine:
id, name, hp, carid
public class EngineModelDto
{
public string Name { get; set; }
public int Hp { get; set; }
public Guid CarId { get; set;}
}
public class EngineTMP
{
public string Name { get; set; }
public int Hp { get; set; }
public List<Guid> CarIds { get; set; }
}
我想做类似这样的伪代码:(但使用自动映射器)
List<EngineModelDto> myListDto = new List<EngineModelDto>();
for(int i = 0; i < CarIds.lenght - 1; i++)
{
var e = new EngineModelDto {
Name = EngineTMP.name,
Hp = EngineTMP.hp,
CarId = EngineTMP.CarIds[i];
}
list.Add(e);
}
这么简单的映射,你也可以手动完成:
var dtos = engineTmp.CarIds.Select(id => new EngineModelDto
{
Name = engineTmp.Name,
Hp = engineTmp.Hp,
CarId = id,
});
但是,如果你坚持使用AutoMapper,你可以这样做:
CreateMap<EngineTMP, IEnumerable<EngineModelDto>>()
.ConvertUsing(src => src.CarIds?.Select(id => new EngineModelDto
{
Name = src.Name,
Hp = src.Hp,
CarId = id,
}));
然后:
var dtos = mapper.Map<IEnumerable<EngineModelDto>>(engineTmp);
我有一个引擎名称、引擎马力和列表 carid 的请求。我怎样才能将 EngineTMP 映射到 EngineModelDto?
Table engine:
id, name, hp, carid
public class EngineModelDto
{
public string Name { get; set; }
public int Hp { get; set; }
public Guid CarId { get; set;}
}
public class EngineTMP
{
public string Name { get; set; }
public int Hp { get; set; }
public List<Guid> CarIds { get; set; }
}
我想做类似这样的伪代码:(但使用自动映射器)
List<EngineModelDto> myListDto = new List<EngineModelDto>();
for(int i = 0; i < CarIds.lenght - 1; i++)
{
var e = new EngineModelDto {
Name = EngineTMP.name,
Hp = EngineTMP.hp,
CarId = EngineTMP.CarIds[i];
}
list.Add(e);
}
这么简单的映射,你也可以手动完成:
var dtos = engineTmp.CarIds.Select(id => new EngineModelDto
{
Name = engineTmp.Name,
Hp = engineTmp.Hp,
CarId = id,
});
但是,如果你坚持使用AutoMapper,你可以这样做:
CreateMap<EngineTMP, IEnumerable<EngineModelDto>>()
.ConvertUsing(src => src.CarIds?.Select(id => new EngineModelDto
{
Name = src.Name,
Hp = src.Hp,
CarId = id,
}));
然后:
var dtos = mapper.Map<IEnumerable<EngineModelDto>>(engineTmp);