After getting automapper to work (previous question), I\'m struggling with another problem (took it to another question, so the first one wouldn\'t be too complicated)...
<The problem is you want to map a destination property (Entity2
) from multiples source property values (Children
, Married
and HasPet
from Model2
and Nickname
from Model1
).
You can solve your situation using an Custom Resolver or with AfterMap method.
Using Custom Resolvers:
You have to create a class inhering from ValueResolver
to define how you will map Entity2
from an SuperModel
:
public class CustomResolver : ValueResolver<SuperModel, Entity2>
{
protected override Entity2 ResolveCore(SuperModel source)
{
return new Entity2
{
Children = source.Model2.Children,
HasPet = source.Model2.HasPet,
Married = source.Model2.Married,
NickName = source.Model1.NickName
};
}
}
Then, use it like this:
CreateMap<SuperModel, SuperEntity>()
.ForMember(dest => dest.Entity1, opt => opt.MapFrom(src => src.Model1))
.ForMember(dest => dest.Entity2, opt => opt.ResolveUsing<CustomResolver>());
Using AfterMap:
You can execute actions after the mapping, so pass the value from Model1.Nickname
to Entity2.Nickname
after the map:
CreateMap<SuperModel, SuperEntity>()
.ForMember(dest => dest.Entity1, opt => opt.MapFrom(src => src.Model1))
.ForMember(dest => dest.Entity2, opt => opt.MapFrom(src => src.Model2))
.AfterMap((m, e) => e.Entity2.NickName = m.Model1.NickName);