Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper Map If Not Null, Otherwise Custom Convert

Tags:

c#

automapper

Here's my code:

Mapper.CreateMap<Foo, Foo2>()    .ForMember(dest => dest.Bar, opt => opt.MapFrom(src => src.Bar == null ? new BarViewModel() : src.Bar)) 

Basically, "BarViewModel" has a parameterless ctor which sets up properties in the class.

So i'm trying to say to AutoMapper:

If the value is null, then use the ctor for the class. otherwise use the mapping you have in place

The above is giving me a C# compiler error. And i'm guessing a cast wouldn't work either.

So is there a AutoMapper trick to do this?

Worst case i could remove that mapping for that property, and just do:

var mapped = Mapper.Map<Foo,Foo2>(src); if (mapped.Bar == null) mapped.Bar = new BarViewModel(); 

But that's a tad ugly.

Ideas?

like image 697
RPM1984 Avatar asked Jul 19 '12 07:07

RPM1984


1 Answers

You can use custom value resolver. The following should work:

Mapper.CreateMap<Foo, Foo2>()    .ForMember(dest => dest.Bar, opt => opt.ResolveUsing(src => src.Bar == null ? new Bar() : Mapper.Map<Bar,Bar2>(src.Bar))) 
like image 113
k0stya Avatar answered Sep 28 '22 09:09

k0stya