【问题标题】:Automapper - Map custom object nested inside List of objectAutomapper - 映射嵌套在对象列表中的自定义对象
【发布时间】:2016-05-26 00:02:37
【问题描述】:

我需要将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());

我被这个问题困扰了好几天,请帮忙。

【问题讨论】:

    标签: c# reflection automapper nested-map


    【解决方案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());
    

    【讨论】:

    • 非常感谢@Tamas Ionut。这么点小事就错过了。感谢您的帮助。
    • 只是指出,即使没有 .AfterMap 部分,映射也是成功的。
    猜你喜欢
    • 2017-07-20
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-03
    • 2012-02-25
    • 2022-01-06
    • 1970-01-01
    相关资源
    最近更新 更多