-
-
Save kradcliffe/1932255 to your computer and use it in GitHub Desktop.
public static class AutoMapperExtensions | |
{ | |
public static IMappingExpression<TSource, TDestination> | |
IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression) | |
{ | |
var sourceType = typeof(TSource); | |
var destinationType = typeof(TDestination); | |
var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType) && x.DestinationType.Equals(destinationType)); | |
foreach (var property in existingMaps.GetUnmappedPropertyNames()) | |
{ | |
expression.ForMember(property, opt => opt.Ignore()); | |
} | |
return expression; | |
} | |
} | |
// USAGE: | |
Mapper.CreateMap<SourceType, DestinationType>() | |
.ForMember(prop => x.Property, opt => opt.MapFrom(src => src.OtherProperty)) | |
.IgnoreAllNonExisting(); |
How can i ignore as per below.
public class User
{
public string FirstName{get;set;}
public string LastName{get;set;}
public string EmailAddress{get;set;}
public virtual Employer Employer { get; set; }
}
public class Employer
{
public int EmployerId { get; set; }
public int UserID { get; set; }
public string EmployerName { get; set; }
public string EmployerPhone { get; set; }
public virtual User User { get; set; }
}
How to ignore EmployerId in auto mapping?
This is a very useful extension for working with types with many properties. Unfortunately, it doesn't work with types that inherit from a base class (line 11 throws a NullReferenceException). One workaround is to provide explicit mappings or ignores for base class properties.
Above extension is not working with Automapper 5.0.2
FROM schdr on stackoverflow. From this answer: http://stackoverflow.com/a/6474397/12706