AutoMapper - how to use a custom value converter inside a custom type converter

How can I use custom value converters inside a custom type converter? This is currently difficult for me to achieve. Do you know how to use this class?


Face converter

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; } } 

Model

 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; } } 

Value converter

 class DictionaryResolver : ValueResolver<int, Dictionary> { protected override Dictionary ResolveCore(int source) { // do something return new Dictionary { Id = source, Name = "Name" }; } } 
+7
c # mapping typeconverter automapper resolver
source share
1 answer

Custom value converters are designed to override the display of a specific member when AutoMapper is about to map objects:

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

However, when you use a custom type recognizer, this requires full control over the display: there is no way to customize the display of one particular element:

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

However, given that you have full control over the type conversion, there is nothing to stop the reuse of the value converter, you just need to reference it specifically: however, you will have to add an open method that returns the protected ResolveCore method:

 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" }; } } 

Then, when converting types, you call it to resolve this property:

 var person = new Person { Name = personData.Name }; DictionaryResolver resolver = new DictionaryResolver(); person.Dic = resolver.Resolve(personData.IntValue); // whatever value you use 
+8
source share

All Articles