AutoMapper地图子属性也定义了地图 [英] AutoMapper Map Child Property that also has a map defined

查看:99
本文介绍了AutoMapper地图子属性也定义了地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的域对象:

public class DomainClass
{
    public int Id { get; set; }

    public string A { get; set; }
    public string B { get; set; }
}



我有我想要映射到以下两个对象:

I have the following two objects that I want to map to:

public class Parent 
{
    public int Id { get; set; }
    public string A { get; set; }

    public Child Child { get; set; }
}

public class Child 
{
    public int Id { get; set; }
    public string B { get; set; }
}



我设置如下图:

I set up the following maps:

 Mapper.CreateMap<DomainClass, Parent>();
 Mapper.CreateMap<DomainClass, Child>();

如果我使用下面的调用则parent.Child属性为null地图我的对象。

If I map my object using the following call then the parent.Child property is null.

var domain = GetDomainObject();
var parent = Mapper.Map<DomainClass, Parent>(domain); // parent.Child is null



我知道我可以写:

I know I can write the following:

var domain = GetDomainObject();
var parent = Mapper.Map<DomainClass, Parent>(domain);
parent.Child = Mapper.Map<DomainClass, Child>(domain);



有没有一种办法可以消除第二个电话,并有AutoMapper为我做到这一点?

Is there a way I can eliminate that second call and have AutoMapper do this for me?

推荐答案

您只需要指定的映射:

Mapper.CreateMap<DomainClass, Child>();
Mapper.CreateMap<DomainClass, Parent>()
      .ForMember(d => d.Id, opt => opt.MapFrom(s => s.Id))
      .ForMember(d => d.A, opt => opt.MapFrom(s => s.A))
      .ForMember(d => d.Child, 
                 opt => opt.MapFrom(s => Mapper.Map<DomainClass, Child>(s)));

这篇关于AutoMapper地图子属性也定义了地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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