AutoMapper: "Ignore the rest"?
Is there a way to tell AutoMapper to ignore all of the properties except the ones which are mapped explicitly?
I have external DTO classes which are likely to change from the outside and I want to avoid specifying each property to be ignored explicitly, since adding new properties will break the functionality (cause exceptions) when trying to map them into my own objects.
This is an extension method I wrote that ignores all non existing properties on the destination. Not sure if it will still be useful as the question is more than two years old, but I ran into the same issue having to add a lot of manual Ignore calls.
public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>
(this IMappingExpression<TSource, TDestination> expression)
{
var flags = BindingFlags.Public | BindingFlags.Instance;
var sourceType = typeof (TSource);
var destinationProperties = typeof (TDestination).GetProperties(flags);
foreach (var property in destinationProperties)
{
if (sourceType.GetProperty(property.Name, flags) == null)
{
expression.ForMember(property.Name, opt => opt.Ignore());
}
}
return expression;
}
Usage:
Mapper.CreateMap<SourceType, DestinationType>()
.IgnoreAllNonExisting();
UPDATE : Apparently this does not work correctly if you have custom mappings because it overwrites them. I guess it could still work if call IgnoreAllNonExisting first and then the custom mappings later.
schdr has a solution (as an answer to this question) which uses Mapper.GetAllTypeMaps()
to find out which properties are unmapped and auto ignore them. Seems like a more robust solution to me.
I've updated Can Gencer's extension to not overwrite any existing maps.
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();
From what I understood the question was that there are fields on the destination which doesn't have a mapped field in the source, which is why you are looking for ways to Ignore those non mapped destination fields.
Instead of implementing and using these extension method you could simply use
Mapper.CreateMap<destinationModel, sourceModel>(MemberList.Source);
Now the automapper knows that it needs to only validate that all the source fields are mapped but not the other way around.
链接地址: http://www.djcxy.com/p/74392.html上一篇: 如何在Ninject.Web.Mvc中使用AutoMapper?
下一篇: AutoMapper:“忽略其余”?