I am trying to map objects with multi-level members: these are the classes:
public class Father { public int Id { get; set; } public Son Son { get; set; } } public class FatherModel { public int Id { get; set; } public int SonId { get; set; } } public class Son { public int Id { get; set; } }
This is how I try automap it:
AutoMapper.Mapper.CreateMap<FatherModel , Father>() .ForMember(dest => dest.Son.Id, opt => opt.MapFrom(src => src.SonId));
this is the exception that I get:
Expression 'dest => Convert(dest.Son.Id)' must resolve to top-level member and not any child object's properties. Use a custom resolver on the child type or the AfterMap option instead. Parameter name: lambdaExpression
Thanks
The problem, as pointed out in the discussion of the above approach, is that AutoMapper does not do a recursive deep clone of nested objects: "...so you better make sure AutoMapper has mappings for member classes that you want to deep copy, and doesn't have mappings for member classes that you want to shallow copy."
With both flattening and nested mappings, we can create a variety of destination shapes to suit whatever our needs may be.
How do I use AutoMapper? First, you need both a source and destination type to work with. The destination type's design can be influenced by the layer in which it lives, but AutoMapper works best as long as the names of the members match up to the source type's members.
If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.
This will work both for mapping to a new or to an existing object.
Mapper.CreateMap<FatherModel, Father>() .ForMember(x => x.Son, opt => opt.MapFrom(model => model)); Mapper.CreateMap<FatherModel, Son>() .ForMember(x => x.Id, opt => opt.MapFrom(model => model.SonId));
AutoMapper.Mapper.CreateMap<FatherModel, Father>() .ForMember(x => x.Son, opt => opt.ResolveUsing(model => new Son() {Id = model.SonId}));
if it's getting more complex you can write a ValueResolver class, see example here- http://automapper.codeplex.com/wikipage?title=Custom%20Value%20Resolvers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With