c# - AutoMapper 更改类型

标签 c# automapper-2 automapper-3

鉴于以下情况:

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<AFooEquipment> .它会看到 object2 在 typeof(B) 类中,所以我转换它的设备 -> List<BFooEquipment> .

这可能吗?

最佳答案

我使用的是 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)它应该给你你想要的。或者我怀疑你想要什么:)

关于c# - AutoMapper 更改类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26495796/

相关文章:

c# - Blazor 无法连接到 ASP.NET Core WebApi (CORS)

c# - 给定一个 List<int> 如何创建一个逗号分隔的字符串?

c# - try/catch 应该在 using block 的内部还是外部?

c# - 使用 AutoMapper 将对象的属性映射到字符串

caSTLe-windsor - CaSTLe Windsor 更新后无法解析 AutoMapper 配置文件

javascript - Mapper 不包含 CreateMap C# 的定义

asp.net-mvc - 多个用户创建用户时修改了 automapper 错误集合

c# - 如何实现像 StringCollection 这样的默认方法和一些类呢?

c# - 带有 ValueFormatter 的 AutoMapper

entity-framework-6 - Automapper 导致错误 : missing type map configuration or unsupported mapping