Adrian Hristov Adrian Hristov - 2 months ago 13
C# Question

How to ignore all properties that are marked as virtual

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?

Answer

You can create a mapping 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;
        }
    }
}

Usage :

Mapper.CreateMap<Source,Destination>().IgnoreAllVirtual();
Comments