AutoMapper使用自定义逻辑更改属性类型,然后为新类型进行映射

时间:2020-08-03 21:49:36

标签: c# .net-core mapping automapper any

我有一个叫做Any的特殊类型,可以在其中保存任何类型的值(例如对象类型)

请考虑以下内容:

class ADto
{
  public Any Foo { get; set; } // Foo has BDto inside of it
}

class A
{
  public object Foo { get; set; } // Foo has B inside of it
}

class BDto
{
  public string Bar { get; set; }
}

class B
{
  public string Bar { get; set; }
}

我已经配置了这样的映射:

cfg.CreateMap<ADto, A>();
cfg.CreateMap<BDto, B>();

我使用自定义逻辑来查找ADto.Foo(即BDto)中实际上是什么类型。

如果我使用自定义TypeConverter:

public class AnyToObjectTypeConverter : ITypeConverter<Any, object>
{
    public object Convert(Any source, object destination, ResolutionContext context)
{
  var underlyingType = FindUnderlyingType(source); //which in case is typeof(ADto)
  // here I need to map from ADto => A, I would like AutoMapper to do this mapping since I configured this mapping in configuration, but how?
???
}
}

然后我如何像通常那样完成对BDto属性的BFoo的映射?

在我的映射中,我只需要执行一个额外的步骤即可找到实际的基础类型!

0 个答案:

没有答案