Automapper映射到嵌套类

Sha*_*ean 16 asp.net-mvc automapper

我有一个类,我需要映射到多个类,例如.

这是我从(视图模型)映射的源:

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

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

    public int CountryId { get; set; }
    public string Country { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是目标类的方式(域模型):

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

    public virtual Location Location { get; set; }
    public virtual int? LocationId { get; set; }
}

public class Location
{
    public int LocationId { get; set; }

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

    public virtual int CountryId { get; set; }
    public virtual Country Country { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

这就是我的automapper创建地图当前的样子:

Mapper.CreateMap<UserBM, User>();
Run Code Online (Sandbox Code Playgroud)

And*_*ker 28

定义两个映射,从同一源映射到不同的目标.在User映射中,Location使用手动映射属性Mapper.Map<UserBM, Location>(...)

Mapper.CreateMap<UserBM, Location>();
Mapper.CreateMap<UserBM, User>()
    .ForMember(dest => dest.Location, opt => 
         opt.MapFrom(src => Mapper.Map<UserBM, Location>(src));
Run Code Online (Sandbox Code Playgroud)

  • 在[SO](http://stackoverflow.com/questions/5984640/automapper-class-and-nested-class-map-to-one-class)上有类似的帖子,我更喜欢映射的最后一点:而不是`opt.MapFrom(src => Mapper.Map <TSrc,TDest>(src)`,它使用更简单的`opt => opt.MapFrom(src => src)` (7认同)