自动映射器包括自定义列表的所有属性

本文关键字:属性 列表 映射 包括 自定义 | 更新日期: 2023-09-27 18:37:04

class SomeObject
{
   public string name {get;set;}
}
class CustomCollection : List<SomeObject>
{
   public int x {get;set;}
   public string z {get;set;}
}
class A
{
   public CustomCollection collection { get ; set; }
}
class B
{
   public CustomCollection collection { get ; set; }
}

// Creating mapping   
Mapper.CreateMap<A, B>();

当我将 A 映射到 B 时,除了自定义集合中的 X 和 Z 之外,所有属性都正确映射。

自定义集合正确获取初始化的某个对象列表,并且 SomeObject.Name 也正确映射。

只有我在集合中声明的自定义属性 X、Z 不会被映射。

我做错了什么?

发现的唯一方法是像下面这样进行映射后,但是它有点违背了使用自动映射器的目的,并且每次我向CustomCollection添加新属性时都会中断。

 Mapper.CreateMap<A, B>().AfterMap((source, destination) => { 
     source.x = destination.x; 
     source.z = destination.z ;
});

自动映射器包括自定义列表<T>的所有属性

当前的映射配置确实会创建一个新CustomCollection但其中的SomeObject项是对源集合中对象的引用。如果这不是问题,您可以使用以下映射配置:

CreateMap<CustomCollection, CustomCollection>()
    .AfterMap((source, dest) => dest.AddRange(source));
CreateMap<A, B>();

如果您也可以b.collection引用a.collection则可以使用以下映射配置:

CreateMap<CustomCollection, CustomCollection>()
    .ConstructUsing(col => col);
CreateMap<A, B>();

AutoMapper不是为克隆而设计的,所以如果你需要,你必须为此编写自己的逻辑。