AutoMapper Ignore Method in C#

AutoMapper Ignore Method in C# with Examples

In this article, I am going to discuss how to use the AutoMapper Ignore Method in C# with Examples. Please read our previous article where we discussed AutoMapper Conditional Mapping in C# with ExamplesAt the end of this article, you will understand the need and use of the AutoMapper Ignore Method in C# with Examples.

Why do we need AutoMapper Ignore Method in C#?

By default, AutoMapper tries to map all the properties from the source type to the destination type when both source and destination type property names are the same. If you want some of the properties not to map with the destination type property then you need to use the AutoMapper Ignore Method in C#.

Note: If some of the properties are not available in the destination type, then AutoMapper will not throw any exception when doing the mapping. However, it will throw an exception when you are using the ValidateMapperConfiguration() which we will discuss in our upcoming articles.

Example to understand AutoMapper Ignore Method in C#

Let us understand how to use the AutoMapper Ignore Method with an example. We are going to use the following Employee and EmployeeDTO classes AutoMapper Ignore Property. Both classes have the same number, same name, and same types of properties.  So, create a class file with the name Employee.cs and then copy and paste the following code into it.

namespace AutoMapperDemo
{
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Email { get; set; }
    }
}

Next, create another class file with the name EmployeeDTO.cs and then copy and paste the following code into it.

namespace AutoMapperDemo
{
    public class EmployeeDTO
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Email { get; set; }
    }
}
Business Requirement:

Our Business Requirement is not to map the Address Property i.e. we need to Ignore the Address Property while doing the mapping between these two objects. To do so we need to use the Ignore Method with the Address property of the destination type while doing the mapper configuration. So, create a class file with the name MapperConfig.cs and copy and paste the following code into it. Here, you can see, using the ForMember method, for the destination Address property, we are calling the Ignore method which will Ignore this property while doing the Mapping.

using AutoMapper;
namespace AutoMapperDemo
{
    public class MapperConfig
    {
        public static Mapper InitializeAutomapper()
        {
            //Configuring AutoMapper
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Employee, EmployeeDTO>()

                    //Ignoring the Address property of the destination type
                    .ForMember(dest => dest.Address, act => act.Ignore());
            });

            //Creating the Mapper Instance
            var mapper = new Mapper(config);

            //returning the Mapper Instance
            return mapper;
        }
    }
}

Next, modify the Main method of the Program class as follows to see whether the Ignore Method of AutoMapper is working as expected or not. The following example code is self-explained, so please go through the comment lines for a better understanding.

using System;
namespace AutoMapperDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize AutoMapper
            var mapper = MapperConfig.InitializeAutomapper();

            //Creating Source Object
            Employee employee = new Employee()
            {
                ID = 101,
                Name = "James",
                Address = "Mumbai",
                Email = "info@dotnettutorials.net"
            };

            //Mapping Source Employee Object with Destination EmployeeDTO Object
            var empDTO = mapper.Map<Employee, EmployeeDTO>(employee);

            //Printing the Employee Object
            Console.WriteLine("After Mapping : Employee Object");
            Console.WriteLine("ID : " + employee.ID + ", Name : " + employee.Name + ", Address : " + employee.Address + ", Email : " + employee.Email);
            Console.WriteLine();

            //Printing the EmployeeDTO Object
            Console.WriteLine("After Mapping : EmployeeDTO Object");
            Console.WriteLine("ID : " + empDTO.ID + ", Name : " + empDTO.Name + ", Address : " + empDTO.Address + ", Email : " + empDTO.Email);
            Console.ReadLine();
        }
    }
}

Now, run the application and you will get the following output.

Example to understand AutoMapper Ignore Method in C#

As you can see in the above output, the value for the Address property is empty even though the Address property for the Source type has value. So, the AutoMapper Ignore() method is used when you want to completely ignore the property in the mapping. The ignored method could be in either the source or the destination object.

How to Ignore Multiple Properties while using AutoMapper in C#?

In our previous example, we have seen how to use Ignore Method with one Property. This is fine if you are Ignoring one or two properties. But, it will become a tedious procedure if you want to ignore multiple properties from mapping. If that is your requirement then do consider creating an extension class that will Ignore the properties based on the data attribute specified in the model. Let us discuss the step-by-step procedure to implement this.

Step1: Create a NoMap Attribute Class

Create a class file with the name NoMapAttribute.cs and then copy and paste the following code into it. Here, you can see, the NoMapAttribute class is inherited from the System.Attribute class. Now, we can use this class as an attribute.

namespace AutoMapperDemo
{
    public class NoMapAttribute : System.Attribute
    {
    }
}
Step2: Decorate the properties with the NoMap attribute

Now, we need to decorate the NoMap Attribute with the source type properties which we don’t want to map with the destination type. For example, if you don’t want to map the Address and Email property, then you need to decorate the NoMap attribute with the Address and Email property of the Employee class. So, modify the Employee class as follows.

namespace AutoMapperDemo
{
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        [NoMap]
        public string Address { get; set; }
        [NoMap]
        public string Email { get; set; }
    }
}
Step3: Creating an Extension Method

Create a class file with the name IgnoreNoMapExtensions.cs and then copy and paste the following code into it. This is going to be a static class and within this static class, we are creating one genetic static method and passing the parameter as IMappingExpression using this keyword. Within this method, we are checking whether the property is decorated with the NoMap Attribute or not. If it is decorated with NoMap Attribute, then we are calling the Ignore method. The following class code is self-explained, so please go through the comment lines for a better understanding.

using AutoMapper;
using System.ComponentModel;
namespace AutoMapperDemo
{
    //Extension Method: 
    //The Class Should Be Static
    //Method Should Be Static
    //First Parameter is the class which which we can access the Method
    public static class IgnoreNoMapExtensions
    {
        //Method is Generic and Hence we can use with any TSource and TDestination Type
        public static IMappingExpression<TSource, TDestination> IgnoreNoMap<TSource, TDestination>(
            this IMappingExpression<TSource, TDestination> expression)
        {
            //Fetching Type of the TSource
            var sourceType = typeof(TSource);

            //Fetching All Properties of the Source Type using GetProperties() method
            foreach (var property in sourceType.GetProperties())
            {
                //Get the Property Name
                PropertyDescriptor descriptor = TypeDescriptor.GetProperties(sourceType)[property.Name];

                //Check if Property is Decorated with the NoMapAttribute
                NoMapAttribute attribute = (NoMapAttribute)descriptor.Attributes[typeof(NoMapAttribute)];
                if (attribute != null)
                {
                    //If Property is Decorated with NoMap Attribute, call the Ignore Method
                    expression.ForMember(property.Name, opt => opt.Ignore());
                }  
            }
            return expression;
        }
    }
}
Step4: Using the IgnoreNoMap Extension Method in Mapper Configuration

In the last step, we need to use the IgnoreNoMap method while defining the Mapping. So, modify the InitializeAutomapper method of the MapperConfig class as follows. Here, you can see, after the Mapping, we are simply calling the IgnoreNoMap method. This IgnoreNoMap Extension method is generic and hence can be used with any other mapping if required.

using AutoMapper;
namespace AutoMapperDemo
{
    public class MapperConfig
    {
        public static Mapper InitializeAutomapper()
        {
            //Configuring AutoMapper
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Employee, EmployeeDTO>()
                .IgnoreNoMap();
            });

            //Creating the Mapper Instance
            var mapper = new Mapper(config);

            //returning the Mapper Instance
            return mapper;
        }
    }
}

With the above changes in place, now run the application, and it will display the following output. Here, you can see, it is Ignoring the Address and Email Property values.

How to Ignore Multiple Properties while using AutoMapper in C#

In the next article, I am going to discuss How to Store Fixed and Dynamic Values in Destination Property in AutoMapper with Examples in C#. Here, in this article, I try to explain the AutoMapper Ignore Method in C# with Examples. I hope this AutoMapper Ignore Method in C# article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *