Digamos que temos esta Entidade e o Dto correspondente:
public class MyEntity
{
public string Name {get; set;}
}
public class MyEntityDto
{
public string Name {get;set;}
}
E este agregado e Dto correspondente:
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;}
}
}
Aqui está o perfil de mapeamento:
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 = ...
}
}));
}
}
Como posso mapear objetos aninhados?
Você deve criar uma regra de mapeamento de
MyEntity
paraMyAggDto.AggDataDto
.Para a regra de mapeamento de
MyAgg
paraMyAggDto
, mapeie oEntity
membro da origem para oData
membro do destino.Uma pequena mudança que faz sentido quando AggDataDto possui mais de uma entidade, que é o meu caso real: