我需要将List<Source>
映射到List<Dest>
,问题是源内包含NestedObject
&amp; Dest中还包含NestedObject
。我的List正在映射时,我也需要映射这两个。我已尝试过所有内容,但嵌套对象始终保持null
并且没有映射,或者我得到以下异常:
缺少类型映射配置或不支持的映射。映射类型: .....
来源与结构的结构目的地:
来源:
public class Source {
public string Prop1 { get; set; }
public CustomObjectSource NestedProp{ get; set; }
}
public class CustomObjectSource {
public string Key { get; set; }
public string Value{ get; set; }
}
目标
public class Destination {
public string Prop1 { get; set; }
public CustomObjectDest NestedProp{ get; set; }
}
public class CustomObjectDest {
public string Key { get; set; }
public string Value{ get; set; }
}
我尝试了什么: 我有以下代码,尝试了其他几种方法,但无济于事:
var config = new MapperConfiguration(c =>
{
c.CreateMap<Source, Destination>()
.AfterMap((Src, Dest) => Dest.NestedProp = new Dest.NestedProp
{
Key = Src.NestedProp.Key,
Value = Src.NestedProp.Value
});
});
var mapper = config.CreateMapper();
var destinations = mapper.Map<List<Source>, List<Destination>>(MySourceList.ToList());
我坚持了好几天,请帮助。
答案 0 :(得分:1)
您还必须将CustomObjectSource映射到CustomObjectDest。
这应该这样做:
var config = new MapperConfiguration(c =>
{
c.CreateMap<CustomObjectSource, CustomObjectDest>();
c.CreateMap<Source, Destination>()
.AfterMap((Src, Dest) => Dest.NestedProp = new CustomObjectDest
{
Key = Src.NestedProp.Key,
Value = Src.NestedProp.Value
});
});
var mapper = config.CreateMapper();
var MySourceList = new List<Source>
{
new Source
{
Prop1 = "prop1",
NestedProp = new CustomObjectSource()
{
Key = "key",
Value = "val"
}
}
};
var destinations = mapper.Map<List<Source>, List<Destination>>(MySourceList.ToList());