Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify a specific type converter for a given property using AutoMapper

How can I override the type converter being used by AutoMapper for a given property?

For example, if I have:

public class Foo
{
    public string Name { get; set; }
}

public class Bar
{
    public string Name { get; set; }
}

Now I simply want to map Foo.Name to Bar.Name but using a specified type converter. I see how I can do it using:

Mapper
    .CreateMap<Foo,Bar>()
    .ForMember( x => x.Name, opt => opt.ResolveUsing<FooNameResolver>() );

But this hard-codes the conversion to use the Name property on Foo. If I have the same type of conversion on other properties in this or other classes, I have to create a resolver class for each.

And I don't want to specify a converter for string -> string as this conversion is specific to this property or others like it.

I just want to override the type converter! I'm sure this must be possible but I'm blanking on it :-(

I'm after something like this:

Mapper
    .CreateMap<Foo,Bar>()
    .ForMember( x => x.Name, opt => opt.Using<MySpecialStringConverter>() );
like image 590
Mike Scott Avatar asked Oct 13 '10 23:10

Mike Scott


1 Answers

I discovered the answer reading through the unit tests for AutoMapper. It's not very obvious, despite the fluent interface, because many of the methods on the mapping options return void. However, ResolveUsing<>() doesn't return void but allows you to specify further options. Herein lies the solution:

Mapper
    .CreateMap<Source,Dest>
    .ForMember( dest => dest.Name, 
                opt => opt.ResolveUsing<MySpecialStringConverter>()
                          .FromMember( source => source.Name ) );

I'd prefer not to have to specify the .FromMember when the property is the default which AutoMapper would use anyway and all I want to use is override the type converter/resolver.

like image 138
Mike Scott Avatar answered Sep 18 '22 15:09

Mike Scott