在自定义类型转换器中调用 Mapper.Map



我知道这个问题已经被问过一次了这里,但没有必要在自定义类型转换器中调用 Automapper.Map() 方法。那么如果我有这种类型的结构呢:

class MyType
{
    public double ValueToBeComputed1 { get; set; }
    public double ValueToBeComputed2 { get; set; }
}
class ComplexType
{
    public double ValueToBeComputed { get; set; }
    public MyType MyProperty { get; set; }
}

对于要计算的所有值,我需要进行不同的演算,因此我将为复杂类型提供一个自定义类型转换器,例如 OtherType。我的问题是我是否能够在该自定义转换器中为属性 MyProperty 调用 Mapper.Map()?

在我面对过时的文档 Automapper 自定义类型转换器之后,其中 ITypeConverter 接口已更改,我在这里找到了答案:ITypeConverter 接口在 AutoMapper 2.0 中已更改,我能够制作一个工作原型,该原型生成转换后的类型如下:

public class ComplexTypeConverter : ITypeConverter<ComplexSourceType, ComplexDestinationType>
{
    public ComplexDestinationType Convert(ResolutionContext context)
    {
        var source = (ComplexSourceType)context.SourceValue;
        return new ComplexDestinationType
        {
            MyProperty = Mapper.Map<SourceType, DestinationType>(source.MyProperty),
            ValueComputed = source.ValueToBeComputed + 10
        };
    }
}
public class TypeConverter : ITypeConverter<SourceType, DestinationType>
{
    public DestinationType Convert(ResolutionContext context)
    {
        var source= (SourceType)context.SourceValue;
        return new DestinationType
        {
            ValueComputed1 = source.ValueToBeComputed1 + 10,
            ValueComputed2 = source.ValueToBeComputed2 + 10
        };
    }
}
class Program
{
    static void Main(string[] args)
    {
        Mapper.Initialize(cfg => {
            cfg.CreateMap<ComplexSourceType, ComplexDestinationType>().ConvertUsing(new ComplexTypeConverter());
            cfg.CreateMap<SourceType, DestinationType>().ConvertUsing(new TypeConverter());
        });
        Mapper.AssertConfigurationIsValid();
        ComplexSourceType source = new ComplexSourceType
        {
            MyProperty = new SourceType
            {
                ValueToBeComputed1 = 1,
                ValueToBeComputed2 = 1
            },
            ValueToBeComputed = 1
        };
        var dest = Mapper.Map<ComplexSourceType, ComplexDestinationType>(source);
    }
}

dest 对象保存修改后的数据,每个属性上有 11

最新更新