automapper automapping deep object to flat object and back

How do you convert a deep object to a flat object and back using automapper?

for instance:

Person 
{
    public string Name { get; set; }
    public Address Address { get; set; }
}

Address
{
    public string City { get; set; }
    public string State { get; set; }
}

FlatObject
{
    public string Name { get; set; }
    public string City { get; set; }
    public string State { get; set; }
}

Two ways you could accomplish this:

  • Define two mappings, one from FlatObject --> Person and another from FlatObject --> Address :

    Mapper.CreateMap<FlatObject, Address>();
    
    Mapper.CreateMap<FlatObject, Person>()
        .ForMember(dest => dest.Address, opt => opt.MapFrom(src => src));
    
  • Define one mapping and create the Address object inside the mapping definition:

    Mapper.CreateMap<FlatObject, Person>()
        .ForMember(
            dest => dest.Address, 
            opt => opt.MapFrom(
                src => new Address { City = src.City, State = src.State }));
    
  • Personally I'd go with option 1. This way if you add properties to FlatObject , you won't have to worry about updating the mapping definition (you would if you used option #2).

    However, @Raphaël is correct in pointing out the author's link that questions the validity of mapping to domain objects.


    Starting from version 6.0.1 you can do with the ReverseMap method, wich is used to create the unflatten map.

    Mapper
      .CreateMap<FlatObject, Person>()
      .ReverseMap();
    

    This creates two maps, the flatten map is used to create the reversed one.

    There is detailed info at the automapper documentation


    Well, AutoMapper is ok for "automatic" flattening, just respect the naming conventions, in your case

    FlatObject {
      public string Name {get;set;}
      public string AddressCity {get;set;}
      public string AddressState {get;set;}
    }
    

    But AFAIK, AutoMapper doesn't do unflattening .

    See this from the author of the library.

    They're other tools that do that (with other kinds of limitations), like ValueInjecter

    链接地址: http://www.djcxy.com/p/6380.html

    上一篇: 在AutoMapper中将复杂类型映射到平面类型

    下一篇: automapper将深层对象自动映射到平面对象并返回