How to ignore all properties marked as virtual

I use the virtual for some of my properties to lazily load EF. I have a case where all the properties in my models marked as virtual should be ignored from AutoMapper when matching the source to the destination.

Is there a way to automatically achieve this, or should I ignore each item manually?

+6
source share
2 answers

You can create a display extension and use it:

 namespace MywebProject.Extensions.Mapping { public static class IgnoreVirtualExtensions { public static IMappingExpression<TSource, TDestination> IgnoreAllVirtual<TSource, TDestination>( this IMappingExpression<TSource, TDestination> expression) { var desType = typeof(TDestination); foreach (var property in desType.GetProperties().Where(p => p.GetGetMethod().IsVirtual)) { expression.ForMember(property.Name, opt => opt.Ignore()); } return expression; } } } 

Using:

 Mapper.CreateMap<Source,Destination>().IgnoreAllVirtual(); 
+21
source

inquisitive answer works fine, but it can be increased for use in real life, when some mappings are performed from data models in the service model, and virtual members from the source type should be ignored.

In addition, if the type implements some interface, these properties will be displayed as virtual, so the condition !IsFinal must be added to remove these false positive virtual properties.

 public static class AutoMapperExtensions { public static IMappingExpression<TSource, TDestination> IgnoreAllDestinationVirtual<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression) { var desType = typeof(TDestination); foreach (var property in desType.GetProperties().Where(p => p.GetGetMethod().IsVirtual && !p.GetGetMethod().IsFinal)) { expression.ForMember(property.Name, opt => opt.Ignore()); } return expression; } public static IMappingExpression<TSource, TDestination> IgnoreAllSourceVirtual<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression) { var srcType = typeof(TSource); foreach (var property in srcType.GetProperties().Where(p => p.GetGetMethod().IsVirtual && !p.GetGetMethod().IsFinal)) { expression.ForSourceMember(property.Name, opt => opt.Ignore()); } return expression; } } 
+1
source

Source: https://habr.com/ru/post/971825/


All Articles