Automapper map from nested class to single (flatten)

☆樱花仙子☆ 提交于 2019-12-21 01:20:16

问题


This is my source:

public class User
{
    public int UserId { get; set; }

    public Address Address { get; set; }
}

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

This is my destination:

public class UserVM
{
    public int UserId { get; set; }

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

How do I do the mapping? The normal create map doesn't work when they say flattening is automatic.


回答1:


If you change your destination class property names to AddressStreet and AddressState, AutoMapper will, by convention, match them to Address.Street and Address.State on the source.

public class UserVM
{
    public int UserId { get; set; }

    public string AddressStreet { get; set; } // User.Address.Street
    public string AddressState { get; set; }  // User.Address.State
}

Alternatively, you leave your destination property names as is and use custom member mappings:

Mapper.CreateMap<User, UserVM>()
    .ForMember(dest => dest.Street, opt => opt.MapFrom(src => src.Address.Street))
    .ForMember(dest => dest.State, opt => opt.MapFrom(src => src.Address.State));

See the AutoMapper documentation for Projection and Flattening for more information.



来源:https://stackoverflow.com/questions/8058783/automapper-map-from-nested-class-to-single-flatten

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!