AutoMapper更改类型

本文关键字:类型 AutoMapper | 更新日期: 2023-09-27 18:27:30

给定以下条件:

var object1 = new A() { Equipment = new List<FooEquipment>() { new FooEquipment() } };
var object2 = new B() { Equipment = new List<FooEquipment>() { new FooEquipment() } );
var list = new List<Foo>() { object1, object2 };

(我继承了一些遗留代码,List应该在A和B的基类中)。

随着一些新的类别,

public class AFooEquipment : FooEquipment
{
}
public class BFooEquipment : FooEquipment
{
}

我可以使用AutoMapper通过检查它们的父项将这些FooEquipments转换为AFooEquipmentBFooEquipment吗?也就是说,在映射器中,我会看到对象1属于(a)类的类型,所以我转换它的设备->List<AFooEquipment>。它会看到对象2属于(B)类的类型,所以我转换它的设备->List<BFooEquipment>

这可能吗?

AutoMapper更改类型

我使用的是AutoMapper 3,所以这可能不适用于您,但一种选择是使用ResolutionContextConstructUsing方法,类似于以下内容:

CreateMap<Foo, Foo>()
  .Include<A, Foo>()
  .Include<B, Foo>();
CreateMap<A, A>();
CreateMap<B, B>();
CreateMap<FooEquipment, FooEquipment>()
  .ConstructUsing((ResolutionContext ctx) =>
  {
    if (ctx.Parent != null) // Parent will point to the Equipment property
    {
      var fooParent = ctx.Parent.Parent; // Will point to Foo, either A or B.
      if (fooParent != null)
      {
        if (fooParent.SourceType == typeof(A)) return new AFooEquipment();
        if (fooParent.SourceType == typeof(B)) return new BFooEquipment();
      }
    }
    return new FooEquipment();
  });

如果你打电话给Mapper.Map<IEnumerable<Foo>>(list),它应该会给你想要的。或者我怀疑你想要什么:)