我有以下域对象:
public class DomainClass
{
public int Id { get; set; }
public string A { get; set; }
public string B { get; set; }
}
我有以下两个要映射到的对象:
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; }
}
我设置了以下地图:
Mapper.CreateMap<DomainClass, Parent>();
Mapper.CreateMap<DomainClass, Child>();
如果我使用以下调用映射我的对象,则 Parent.Child 属性为 null。
var domain = GetDomainObject();
var parent = Mapper.Map<DomainClass, Parent>(domain); // parent.Child is null
我知道我可以写以下内容:
var domain = GetDomainObject();
var parent = Mapper.Map<DomainClass, Parent>(domain);
parent.Child = Mapper.Map<DomainClass, Child>(domain);
有没有办法可以消除第二次调用并让 AutoMapper 为我做这件事?
您只需要在映射中指定:
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)));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)