I am using virtual
keyword for some of my properties for EF lazy loading. I have a case in which all properties in my models that are marked as virtual
should be ignored from AutoMapper when mapping source to destination.
Is there an automatic way I can achieve this or should I ignore each member manually?
You can create a mapping extension and use it:
Usage :
To correct the answer of @Alexei, don't use the
ForSourceMember
method, like it's answered here in this issu on github. It's just for validation.An other way is to use
ForAllPropertyMaps
like in this answer.inquisitive
's answer works fine, but it can be augmented for real life usage, when some mappings are performed from data models to service models and virtual members from source type should be ignored.Also, if the type implements some interface, those properties will appear as virtual, so
!IsFinal
condition must be added to remove these false positive virtual properties.As we were using some virtual properties, I had to rewrite the extension as follows:
In essence I check if the property either is of type
ICollection<>
or if it has the[ForeignKey]
attribute.