假设我们有这个实体和相应的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
的映射规则。
对于从
MyAgg
到 MyAggDto
的映射规则,将源的 Entity
成员映射到目标的 Data
成员。
public class MyProfile : Profile
{
public MyProfile()
{
CreateMap<MyEntity, MyEntityDto>();
CreateMap<MyEntity, MyAggDto.AggDataDto>()
.ForMember(dest => dest.Entity, opt => opt.MapFrom(src => src));
CreateMap<MyAgg, MyAggDto>()
.ForMember(dest => dest.Data, opt => opt.MapFrom(src => src.Entity));
}
}