【问题标题】:C# Automapper inner list from another inner list of different typeC# Automapper 内部列表来自另一个不同类型的内部列表
【发布时间】:2020-07-11 22:35:34
【问题描述】:

我正在尝试映射类似于此模型的东西:

class Source {
   ...
   SubSource subSource;
}

class SubSource {
   ...
   List<SourceListItem> list;
   SomeInfo someInfo;
   ...
}

class SomeInfo {
   string name;
   ...
}

class SourceModel {
   ...
   SomeInfoModel someInfoModel;
   ...
}

class SomeInfoModel {
   string name;
   List<SourceListItemModel> list;
   ...
}

我需要将“SubSource.List”映射到“SomeInfoModel.List”。我能够正确映射所有其他属性,但映射后列表始终为空,并且在执行过程中不会发生错误。

我有以下映射配置:

CreateMap<SourceListItem, SourceListItemModel>()
CreateMap<SomeInfo, SomeInfoModel>()
CreateMap<Source, SourceModel>()
 ...
 .ForPath(dest => dest.someInfoModel.list, opt => opt.MapFrom(src => 
 src.subSource.list))
...

【问题讨论】:

  • 我认为你应该提供 SourceListItem 和 SourceListItemModel 类的定义
  • 如果需要我可以添加它们,我只是跳过它们,因为它们是具有简单属性(字符串、整数等)的普通对象

标签: c# .net-core automapper


【解决方案1】:

执行您的代码,对configuration.AssertConfigurationIsValid(); 的调用会引发异常,其中清楚地描述了您遇到的问题

找到未映射的成员。查看下面的类型和成员。添加一个 自定义映射表达式,忽略,添加自定义解析器,或修改 源/目标类型。

对于没有匹配的构造函数,添加一个无参数的ctor,添加可选的 参数,或映射所有构造函数参数

SomeInfo -> SomeInfoModel (目标成员列表) SomeInfo -> SomeInfoModel(目标成员列表)

未映射的属性:列表

可以参考the documentation

【讨论】:

    【解决方案2】:

    试图重现,但对我来说 list 属性的映射有效。

    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<SourceListItem, SourceListItemModel>();
        cfg.CreateMap<SomeInfo, SomeInfoModel>();
        cfg.CreateMap<Source, SourceModel>()
            .ForPath(dest => dest.someInfoModel.list, opt => opt.MapFrom(src =>
             src.subSource.list));
        });
    
    var source = new Source()
    {
        subSource = new SubSource()
        {
            list = new List<SourceListItem>()
            {
                new SourceListItem() { Text1 = "text1" },
                new SourceListItem() { Text1 = "text2" },
            }
        }
    };
    var mapper = new Mapper(config);
    var model = mapper.Map<SourceModel>(source);
    

    使用的模型:

    public class SourceListItem
    {
        public string Text1 { get; set; }
    }
    public class SourceListItemModel
    {
        public string Text1 { get; set; }
    }
    

    【讨论】:

    • 如果你打电话给configuration.AssertConfigurationIsValid();会发生什么?
    • 它说SomeInfoModel中的list属性没有映射到SomeInfo -> SomeInfoModel,这是真的。
    猜你喜欢
    • 2018-08-11
    • 2011-09-27
    • 2013-02-11
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    相关资源
    最近更新 更多