Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep level mapping using Automapper

Tags:

c#

automapper

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

like image 613
SexyMF Avatar asked Mar 21 '13 17:03

SexyMF


People also ask

Does AutoMapper do deep copy?

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."

Does AutoMapper map nested objects?

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 to list a map?

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.

When should you not use AutoMapper?

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.


2 Answers

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)); 
like image 50
Allrameest Avatar answered Sep 22 '22 15:09

Allrameest


    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

like image 33
Maxim Avatar answered Sep 23 '22 15:09

Maxim