How to ignore all properties that are marked as virtual
.net, automapper, c#
Solution
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();
Problem
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?