Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper: What is the Difference Between ForMember and ForSourceMember?

Tags:

automapper

I'm new to AutoMapper, so this is probably a beginner's question. I've searched, but haven't seen this discussed. When creating a map, what is the difference between the ForMember and ForSourceMember methods:

            Mapper.CreateMap<Role, RoleDto>()
            .ForMember(x => x.Users, opt => opt.Ignore())
            .ForSourceMember(x => x.Users, opt => opt.Ignore());

I'm maintaining code written by others. In some places, I see ForMember, in others ForSourceMember, and as shown above, in one place both.

What's the difference between the two?

Thanks in advance for any assistance.

like image 451
WindsorRick Avatar asked Nov 11 '15 21:11

WindsorRick


People also ask

Does AutoMapper work both ways?

We can map both directions, including unflattening: var configuration = new MapperConfiguration(cfg => { cfg. CreateMap<Order, OrderDto>() . ReverseMap(); });

How does AutoMapper work in C#?

AutoMapper in C# is a library used to map data from one object to another. It acts as a mapper between two objects and transforms one object type into another. It converts the input object of one type to the output object of another type until the latter type follows or maintains the conventions of AutoMapper.


1 Answers

Look at the method signatures. In ...

Mapper.CreateMap<Role, RoleDto>()
           .ForMember(x => x.Users, opt => opt.Ignore())
           .ForSourceMember(x => x.Users, opt => opt.Ignore());

... ForMember is a method that expects an Expression<Func<RoleDto>> parameter named destinationMember, whereas ForSourceMember expects an Expression<Func<Role>> parameter named sourceMember. So

  • ForMember configures members of the target type.
  • ForSourceMember configures members of the source type.

In your case, both the source and the target types have members UserId, so the calls look the same, but they aren't. They should do the same thing, but the funny thing is that ForSourceMember doesn't seem to have any effect in ignoring members. Maybe it's a bug.

like image 189
Gert Arnold Avatar answered Oct 19 '22 09:10

Gert Arnold