AutoMapper.Attributes icon indicating copy to clipboard operation
AutoMapper.Attributes copied to clipboard

Using two MapsFromAttribute on both base and inherited class ruins the latter's mappings.

Open AgentFire opened this issue 8 years ago • 1 comments

PasteBin: https://pastebin.com/nGYL300T

The repro above shows a weird bug in the system:

When we have class B inherited from class A, and both are decorated with independent MapsFrom attributes with appropriate ConfigureMapping methods, the B's class mappings are ignored for some reason.

The method ConfigureMapping on the B's attribute is actually ran, but is ignored and the Mapper.Map produces a result which we would expect to be when the ConfigureMapping method would not exist at all - so the custom mappings are gone.

If we remove the custom MapsFrom attribute from the A class, however, the bug does not appear. If we manually set the custom mapping to B (via Mapper.CreateMap), the bug does not appear.

AgentFire avatar Jan 16 '18 17:01 AgentFire

This 'bug' is happening because there are two MapsFrom on one class (including inherited), they overlap, the right one is called first, and the inherited one is called last, so it replaces the mapping. Its ConfigureMapping method isn't called, since it has the signature of a base type, and hence the mapping stays empty.

Found two possible ways to fix the bug:

  1. Add AttributeUsage to all inheritors of MapsFrom, and add the Inherited = false to it.
  2. Remove the true from t.GetCustomAttributes(typeof(MapsToAttribute), true) line.
  3. there are more ways.

AgentFire avatar Apr 29 '18 20:04 AgentFire