自动映射器 - 映射嵌套在对象列表中的自定义对象
本文关键字:对象 映射 列表 自定义 嵌套 | 更新日期: 2023-09-27 18:34:33
我需要将List<Source>
映射到List<Dest>
,问题是Source内部包含NestedObject
,而Des内部也包含一个NestedObject
。在我的列表被映射时,我也需要映射这两个。我已经尝试了所有方法,但嵌套对象始终保持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());
我被困了好几天,请帮忙。
您还必须将 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());