【问题标题】:AutoMapper Change TypeAutoMapper 更改类型
【发布时间】:2014-12-17 05:09:27
【问题描述】:

鉴于以下情况:

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 吗? IE。在映射器中,我会看到 object1 在 typeof(A) 类中,因此我将其设备转换为 -> List&lt;AFooEquipment&gt;。它会看到 object2 在 typeof(B) 类中,所以我转换它的设备 -> List&lt;BFooEquipment&gt;.

这可能吗?

【问题讨论】:

  • 是的,实际上很容易。
  • 我在代码的另一部分成功地使用了这种方法。我为此实例尝试过,但似乎没有用。如果这绝对是正确的方法,也许我的映射错误
  • 这种方法如何在使用 AFooEquipment 或 BFooEquipment 之间进行选择?

标签: c# automapper-2 automapper-3


【解决方案1】:

我正在使用 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&lt;IEnumerable&lt;Foo&gt;&gt;(list),它应该会给你你想要的。或者我怀疑你想要什么:)

【讨论】:

    猜你喜欢
    • 2016-08-11
    • 1970-01-01
    • 2013-04-05
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多