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

Paw*_*aga 9 c# mapping typeconverter resolver automapper

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


人转换器

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

模型

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; }
}
Run Code Online (Sandbox Code Playgroud)

价值解析器

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

stu*_*rtd 10

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

Mapper.CreateMap<PersonData, Person>()
                .ForMember(dest => dest.Dic, opt => opt.ResolveUsing<DictionaryResolver>());
Run Code Online (Sandbox Code Playgroud)

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

Mapper.CreateMap<TPersonData, Person>().ConvertUsing(PersonConverter ); // No ForMember here.
Run Code Online (Sandbox Code Playgroud)

然而,鉴于你类型转换过程中完全控制,有来自阻止你重用值转换器什么都没有,你就必须明确引用它:但是你将不得不增加它返回的保护方法的公共方法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"
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

DictionaryResolver resolver = new DictionaryResolver();
person.Dic = resolver.Resolve(personData.IntValue); // whatever value you use
Run Code Online (Sandbox Code Playgroud)