asp.net-mvc – Automapper映射到嵌套类

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – Automapper映射到嵌套类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个类,我需要t映射到多个类,例如.

这是我从(查看模型)映射的源:

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; }
}

这是目的地类是(域模型):

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; }

}

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

Mapper.CreateMap<UserBM,User>();

解决方法

定义两个映射,从同一个源映射到不同的目的地.在用户映射中,使用Mapper.Map< UserBM,Location>(…)手动映射Location属性
Mapper.CreateMap<UserBM,Location>();
Mapper.CreateMap<UserBM,User>()
    .ForMember(dest => dest.Location,opt => 
         opt.MapFrom(src => Mapper.Map<UserBM,Location>(src));

猜你在找的asp.Net相关文章