AutoMapper - Ignoring Properties

In this post I will show you how to ignore properties from getting mapped automatically by AutoMapper. Suppose if both the source and destination has got a property with same name, but is used for representing different information, in that case we definitly not want the property to be mapped automatically. We can configure this while creating the mapping in AutoMapper as follows.

Syntax 

var config = new MapperConfiguration(cfg => { 
    cfg.CreateMap<Source, Destination>().ForMember(x =>x.DestinationPropertyName, opt => opt.Ignore());
});

Example

var config = new MapperConfiguration(cfg => { 
    cfg.CreateMap<Person, PersonVM>().ForMember(x =>x.Name, opt => opt.Ignore());
});

Since AutoMapper supports FluentAPI, you will be able to call ForMember methods multiple time if you ignore more than one property

var config = new MapperConfiguration(cfg => { 
cfg.CreateMap<Foo, FooCopy>()
.ForMember(x =>x.Name, opt => opt.Ignore())
.ForMember(x => x.Age , opt => opt.Ignore() );
});

In this example, while creating the mapping I have added the ForMember method to ignore the Name property while doing the mapping. If you look at the output window you can see that the value for Name is empty even though the property in the source instance has value in it

It will be a tedious procedure if we want to ignore a significant amount of properties from getting mapped automatically. So if you ever face that scenario do consider creating an extention class like the one below which ignores the properties based on data attribute specified in the model

In this example I have created an empty custom attribute named NoMap by inheriting the Attribute class. After that I decorated the properties which needs to be ignored in the source class with the newly created attribute [NoMap]. Then in the extensions method, I just checked whether a property has this attribute then it's get added to the ignored list

The above example is a based on the solution provided by Vinkal in StackOverflow

Note: All these examples are based on 4.2.1 version of AutoMapper and there's some significant changes in library by removing the static API. Please refer here for futher details


No Comments

Add a Comment

Recent Posts