Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper: Using the structure returned by a custom resolver

Tags:

c#

automapper

With AutoMapper, I am using a ValueResolver that returns a structure like this

struct MyStruct
{
        public int propA;
        public int propB;
        public int propC;
}

class MyResolver : ValueResolver<MyViewModel, MyStruct>
{ 
     protected override MyStruct ResolveCore(MyViewModel source)
     {
      ....return MyStruct data
     }
}

I returned a structure because the mapping rules are quite complex and I could not write a custom resolver for each properties as they are related to each other.

So my idea was to do this in one resolver that return a structure and use itike this

AutoMapper.Mapper.CreateMap<MyViewModel, myData>()
    .ForMember(dest => dest.SomePropA, src => src.ResolveUsing<MyResolver>().propA))
    .ForMember(dest => dest.SomePropB, src => src.ResolveUsing<MyResolver>().propB))

Unfortunately, this does not work.

It looks like src.ResolveUsing<MyResolver>() is not returning a structure

Any help is more than appreciated.

Thanks.

like image 853
user385411 Avatar asked Feb 25 '23 18:02

user385411


1 Answers

By using FromMember you can pass a property from the source to your ValueResolver.

You can use something like this:

.ForMember(dest => dest.SomePropA, opt=> opt.ResolveUsing<MyResolver>().FromMember(src => src.propA))

If you don't specify FromMember, AutoMapper will pass the source to your ValueResolver.

like image 99
CGK Avatar answered Mar 05 '23 02:03

CGK