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.
We can map both directions, including unflattening: var configuration = new MapperConfiguration(cfg => { cfg. CreateMap<Order, OrderDto>() . ReverseMap(); });
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With