C# 如何映射到get-only目标子对象?
我有一个类似于这些的源和目标类型C# 如何映射到get-only目标子对象?,c#,automapper,C#,Automapper,我有一个类似于这些的源和目标类型 public class Source { public int A { get; set; } public SourceChild Child { get; } = new SourceChild (); } public class SourceChild { public int B { get; set; } } public class Destination { public int A { get; set;
public class Source {
public int A { get; set; }
public SourceChild Child { get; } = new SourceChild ();
}
public class SourceChild {
public int B { get; set; }
}
public class Destination {
public int A { get; set; }
public DestinationChild Child { get; } = new DestinationChild();
}
public class DestinationChild {
public int B { get; set; }
}
我以一种简单的方式在概要文件中创建映射,而不需要任何额外的配置
...
this.CreateMap<Source, Destination>();
this.CreateMap<SourceChild, DestinationChild>();
...
我希望destination.Child.B
等于2
我已尝试为目标成员子项添加UseDestinationValue
配置,但没有更改任何内容
如有任何意见,将不胜感激
更新
我没有预料到这一点,但在这样的映射配置中使用显式的MapFrom
时,它似乎会起作用
...
this.CreateMap<Source, Destination>()
.ForMember(e => e.Child, o => o.MapFrom(e => e.Child));
this.CreateMap<SourceChild, DestinationChild>();
...
。。。
这个
.ForMember(e=>e.Child,o=>o.MapFrom(e=>e.Child));
这个.CreateMap();
...
所以我的下一个问题是为什么需要这样做?按照惯例,这难道不是默认行为吗
更新2
更进一步,如果我在根对象中有一个get-only-childList
属性,它也不会映射,除非我添加显式的MapFrom
。但是,如果我在get onlyDestinationChild
中有一个get only-child列表
属性,那么它将很好地从soruce中填充。我觉得这里有一些不一致的行为。是的,但这只是历史。您需要地图from
@LucianBargaoanu谢谢您的评论。请你再澄清一点,你说“是”的确切意思是什么,以及你所说的“历史”是什么意思?如果您有时间将答案与相应文档(我还没有找到)的链接放在一起,那就太好了。您应该能够在AM回购协议中找到讨论这一问题的地方。
...
this.CreateMap<Source, Destination>()
.ForMember(e => e.Child, o => o.MapFrom(e => e.Child));
this.CreateMap<SourceChild, DestinationChild>();
...