I have a source object like so:
public class ParentDto
{
public List<EntityDto> EntityDtos { get; set; }
// some other stuff...
}
and a destination object like so:
public class SomeModel
{
[Key]
public Guid Id { get; set; }
public Entity Entity { get; set; }
}
In a different part of my application I already map my EntityDto to my Entity by using Profiles:
CreateMap<EntityDto, Entity>()
.ForMember(dest => dest.Member,
opt => opt.MapFrom(src => DoSomeStuff(src.AnotherMember)))
.ForMember(dest => dest.YetAnotherMember,
opt => opt.MapFrom(src => DoSomeOtherStuff(src.Whatever)));
Is it possible to reuse this map in order to also map my parent object Dto, which includes a list of entityDtos?
CreateMap<ParentDto, SomeModel>()
.ForMember(dest => dest.Id,
opt => opt.Ignore())
// some more stuff...
// This is where I am struggling!
.ForMember(dest => dest. Entity,
opt => opt.MapFrom(src => src.EntityDtos[0]));
How would I address the fact that I have already a mapping for EntityDto to Entity and the fact that I have to deal with the list?
One has nothing to do with the other. The mappings you define are utilized based on the types of the object(s) that are fed into it and/or the generic type param(s) specified. In other words, something like _mapper.Map<SomeModel>(parentDto)
will use the CreateMap<ParentDto, SomeModel>
definition, while _mapper.Map<Entity>(entityDto)
would use the CreateMap<EntityDto, Entity>
definition.
Now, when AutoMapper gets to mapping the collection property, it will by default use the definition for EntityDTO->Entity mapping, but if you specify a custom mapping via MapFrom
, for example, then that will take precedence.