Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 531
Adrian Hristov Avatar asked Jul 06 '14 14:07

Adrian Hristov


People also ask

How to ignore some properties in AutoMapper?

If you want some of the properties not to map with the destination type property then you need to use the AutoMapper Ignore Property in C#. Note: If some of the properties are not available in the destination type, then the AutoMapper will not throw any exception when doing the mapping.

How to ignore a property in c#?

To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.


1 Answers

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();
like image 141
inquisitive Avatar answered Sep 23 '22 09:09

inquisitive