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

时间:2016-06-13 09:50:01

标签: c# automapper

我知道这个问题曾被问过一次 here但是没有必要在自定义类型转换器中调用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; }
}

对于要计算的所有值,我需要进行不同的微积分,因此我将为复杂类型设置一个自定义类型转换器,让我们说其他类型。我的问题是,如果我能够在自定义转换器中为属性MyProperty调用Mapper.Map()?

1 个答案:

答案 0 :(得分:2)

在我面对Automapper自定义类型转换器的过时文档后,更改了ITypeConverter接口,我在这里找到了答案: ITypeConverter interface has been changed in 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