我需要映射List<Source>
到List<Dest>
,问题是 Source 包含NestedObject
在其中,Dest 也包含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());
我被困了好几天,请帮忙。