加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 22:50:46 所属栏目:asp.Net 来源:网络整理
导读:我有一个类,我需要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 str
我有一个类,我需要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));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读