How to ignore all non existing properties on the destination?
See original GitHub issueHello guys,
We have a huge project using AutoMapper 2.x with static scope, and we are on a refactoring time and one of the itens on our backlog is to update AutoMapper to the last version (5.2). We saw that the static scope still exists (we want to keep it) and it is difficult to change now! š¦
In the AutoMapper 2.0, we have an extension method called IgnoreAllNonExisting, which just add a Ignore statement on the properties in the TSource that does not exists in the TDestionation. Look the code:
public static IMappingExpression<TSource, TDestination>IgnoreAllNonExisting<TSource, TDestination>
(this IMappingExpression<TSource, TDestination> expression)
{
var sourceType = typeof(TSource);
var destinationType = typeof(TDestination);
var existingMaps = Mapper.Configuration.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;
}
the problem is that the Mapper.Configuration throws an exception when the program hits it:
āMapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if youāre using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.ā
Then, following some instructions on another threads, I try to modify this method to this:
public static IMappingExpression<TSource, TDestination>IgnoreAllNonExisting<TSource, TDestination>
(this IMappingExpression<TSource, TDestination> expression)
{
expression.ForAllOtherMembers(x => x.Ignore());
return expression;
}
But this method just add the default value for each property on the destination result, making the destination result object get like an empty object with all null properties and 0 (for numbers).
My question: is there any new way to implement this method to ignore properties that does not exists in the TDestination? Maybe a native method? Or how can I fix the existent method?
Thank you
PS: Help/Save us Jimmy š¦ haha
Issue Analytics
- State:
- Created 7 years ago
- Comments:11 (5 by maintainers)
Top Related StackOverflow Question
Yeah keep that static stuff. And this seems to be a very popular post from Stack Overflow that describes a wrong way to do things.
What you really want to do is either:
This āIgnoreAllNonExistingā was a hack pretty much, so instead I have the ability to tell AutoMapper which list of members you want to validate against. Thatās the intent of IgnoreAllNonExisting anyway. So just get rid of that extension method, and everywhere itās being used, Iād pass in to CreateMap, āMemberList.Noneā.
Iāve tried to up vote this on SO:
http://stackoverflow.com/a/31182390/58508