假设我们有这个实体和相应的 Dto:
public class MyEntity
{
public string Name {get; set;}
}
public class MyEntityDto
{
public string Name {get;set;}
}
这个 Aggregate 和相应的 Dto:
public class MyAgg
{
public string SomeProp {get;set;}
public MyEntity Entity {get;set;}
}
public class MyAggDto
{
public string SomeProp {get;set;}
public AggDataDto Data {get;set;}
public class AggDataDto
{
public MyEntityDto Entity {get;set;}
}
}
这是映射配置文件:
public class MyProfile : Profile
{
public MyProfile()
{
CreateMap<MyEntity, MyEntityDto>();
CreateMap<MyAgg, MyAggDto>()
.ForMember(dest => dest.Data, opt => opt.MapFrom(src => {
return new MyAggDto.AggDataDto
{
/*
Can I inject and use IMapper here to get MyEntityDto from src.Entity ?
Should I create the Dto with new MyEntityDto(...) ?
Any other approach ?
*/
Entity = ...
}
}));
}
}
如何映射嵌套对象?
MyEntity
您应该创建一个从到 的映射规则MyAggDto.AggDataDto
。对于映射规则 from
MyAgg
toMyAggDto
,将源的Entity
成员映射到目标的Data
成员。当 AggDataDto 有多个实体时,这是有意义的一个小变化,这是我的真实案例: