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?
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With