AutoMapper - 如何在自定义类型转换器中使用自定义值解析器

时间:2015-10-15 09:17:59

标签: c# mapping automapper typeconverter resolver

如何在自定义类型转换器中使用自定义值解析器? 目前,在我看来很难实现。你知道如何使用这门课吗?

人员转换器

class PersonConverter : ITypeConverter<PersonData, Person>
{
    public Person Convert(ResolutionContext context)
    {
        var personData = context.SourceValue as PersonData;
        if (personData == null)
        {
            return null;
        }

        var person = new Person
        {
            Name = personData.Name
        };
        //person.Dic = // use here my DictionaryResolver

        return person;
    }
}

模型

class Person
{
    public string Name { get; set; }
    public Dictionary Dic { get; set; }
}

class PersonData
{
    public string Name { get; set; }
    public int DicId { get; set; }
}

class Dictionary
{
    public int Id { get; set; }
    public string Name { get; set; }
}

价值解析器

class DictionaryResolver : ValueResolver<int, Dictionary>
{
    protected override Dictionary ResolveCore(int source)
    {
        // do something
        return new Dictionary
        {
            Id = source,
            Name = "Name"
        };
    }
}

1 个答案:

答案 0 :(得分:10)

自定义值解析器用于在AutoMapper要映射对象时覆盖特定成员的映射:

Mapper.CreateMap<PersonData, Person>()
                .ForMember(dest => dest.Dic, opt => opt.ResolveUsing<DictionaryResolver>());

但是,当您使用自定义类型解析程序时,这将完全控制映射:无法自定义一个特定成员的映射方式:

Mapper.CreateMap<TPersonData, Person>().ConvertUsing(PersonConverter ); // No ForMember here.

但是,鉴于您在类型转换期间完成完全控制,没有什么可以阻止您重复使用值转换器,您只需要专门引用它:但是您必须添加一个公共方法返回受保护的方法ResolveCore

class DictionaryResolver : ValueResolver<int, Dictionary>
{
    public Dictionary Resolve(int source)
    {
        return ResolveCore(source);
    }

    protected override Dictionary ResolveCore(int source)
    {
        // do something
        return new Dictionary
        {
            Id = source,
            Name = "Name"
        };
    }
}

然后在类型转换期间,您调用它来解析该属性:

var person = new Person
    {
        Name = personData.Name
    };

DictionaryResolver resolver = new DictionaryResolver();
person.Dic = resolver.Resolve(personData.IntValue); // whatever value you use