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.
As of AutoMapper 5.0, the
.TypeMap
property onIMappingExpression
is gone, meaning the 4.2 solution no longer works. I've created a solution which uses the original functionality but with a different syntax:Implementation:
For those who are using the non-static API in version 4.2.0 and above, the following extension method (found here in the
AutoMapperExtensions
class) can be used:The important thing here is that once the static API is removed, code such as
Mapper.FindTypeMapFor
will no longer work, hence the use of theexpression.TypeMap
field.For Automapper 5.0 in order to skip all unmapped properties you just need put
.ForAllOtherMembers(x=>x.Ignore());
at the end of your profile.
For example:
In this case only Id field for output object will be resolved all other will be skipped. Works like a charm, seems we don't need any tricky extensions anymore!
You can use ForAllMembers, than overwrite only needed like this
Be carefull, it will ignore all, and if you will not add custom mapping, they are already ignore and will not work
also, i want to say, if you have unit test for AutoMapper. And you test that all models with all properties mapped correctly you shouldn't use such extension method
you should write ignore's explicitly
I've updated Can Gencer's extension to not overwrite any existing maps.
Usage:
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.
Usage:
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.