Automapper地图为嵌套类 [英] Automapper map into nested class

查看:162
本文介绍了Automapper地图为嵌套类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有1类,我需要T映象成多个类别,例如为

I have 1 class that I need t map into multiple classes, for eg.

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

This is the source that I'm mapping from(view model):

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

这是目标类是如何(域模型):

This is how the destination class is(domain model):

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如何创建地图目前的样子:

This is how my automapper create map currently looks:

Mapper.CreateMap<UserBM, User>();


推荐答案

定义两个映射,来自相同源到不同的目的地都映射。在用户映射,映射属性手动使用 Mapper.Map&LT的位置; UserBM,地点&gt (......)

Define two mappings, both mapping from the same source to different destinations. In the User mapping, map the Location property manually using 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));

这篇关于Automapper地图为嵌套类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆