AutoMapper Ignore Property in C#

AutoMapper Ignore Property in C# with Examples

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

Why do we need AutoMapper Ignore Property 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 same. If you want some of the properties not to map with the destination type property then you need to use the AutoMapper Ignore Property in C#.

Note: If some of the properties are not available in the destination type, then the 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 Property in C#

Let us understand how to use the AutoMapper Ignore Property with an example. We are going to use the below Employee and EmployeeDTO classes for this demo.

AutoMapper Ignore Property in C#

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 Property with the Address property of the destination type while doing the mapper configuration as shown below in the below image.

AutoMapper Ignore Property in C#

As you can see in the above example, we have added the ForMember method to ignore the Address property while doing the mapping.

Below is the complete example.
using System;
using AutoMapper;
namespace AutoMapperDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var mapper = InitializeAutomapper();

            Employee employee = new Employee()
            {
                ID = 101,
                Name = "James",
                Address = "Mumbai"
            };

            var empDTO = mapper.Map<Employee, EmployeeDTO>(employee);

            Console.WriteLine("After Mapping : Employee");
            Console.WriteLine("ID : " + employee.ID + ", Name : " + employee.Name + ", Address : " + employee.Address);
            Console.WriteLine();
            Console.WriteLine("After Mapping : EmployeeDTO");
            Console.WriteLine("ID : " + empDTO.ID + ", Name : " + empDTO.Name + ", Address : " + empDTO.Address);
            Console.ReadLine();
        }

        static Mapper InitializeAutomapper()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Employee, EmployeeDTO>()

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

            var mapper = new Mapper(config);
            return mapper;
        }
    }

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

    public class EmployeeDTO
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }
}

When we run the application, it will give us the below output.

Ignore Using AutoMapper in C#

If you look at the output window you can see that 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 property could be in either the source or the destination object.

Best way to ignore multiple properties:

But, it will be a tedious procedure if you want to ignore multiple properties from mapping. If that is your requirement then do consider creating an extension class which will ignore the properties based on data attribute specified in the model. Let us discuss the step by step procedure to implement this.

Step1: Create a NoMap Attribute

Create a class with the name NoMapAttribute by inheriting from the System.Attribute class so that we can use this class as an attribute.

Creating NoMap Attribute in C#

Step2: Decorate the properties with the NoMap attribute

Now, you need to decorate the NoMap attribute with the source type properties which you 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 Address and Email property of the Employee class as shown in the below image.

Decorating the Properties with NoMap Attribute

Step3: Creating an extension method

Create an extension class as shown below which will ignore the properties which will decorate with the NoMap attribute. Here, you need to import the System.ComponentModel namespace.

Creating IgnoreNoMap Extension Method

Step4: Using the IgnoreNoMap extension method

Finally you need to use the IgnoreNoMap method while defining the Mapping as shown below.

Calling the NoMapExtension Method to ignore multiple properties in C#

Below is the complete code.
using System;
using System.ComponentModel;
using AutoMapper;
namespace AutoMapperDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var mapper = InitializeAutomapper();

            Employee employee = new Employee()
            {
                ID = 101,
                Name = "James",
                Address = "Mumbai"
            };

            var empDTO = mapper.Map<Employee, EmployeeDTO>(employee);

            Console.WriteLine("After Mapping : Employee");
            Console.WriteLine("ID : " + employee.ID + ", Name : " + employee.Name + ", Address : " + employee.Address + ", Email : " + employee.Email);
            Console.WriteLine();
            Console.WriteLine("After Mapping : EmployeeDTO");
            Console.WriteLine("ID : " + empDTO.ID + ", Name : " + empDTO.Name + ", Address : " + empDTO.Address + ", Email : " + empDTO.Email);
            Console.ReadLine();
        }

        static Mapper InitializeAutomapper()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Employee, EmployeeDTO>()
                .IgnoreNoMap(); ;
            });

            var mapper = new Mapper(config);
            return mapper;
        }
    }
    
    public class NoMapAttribute : System.Attribute
    {
    }

    public static class IgnoreNoMapExtensions
    {
        public static IMappingExpression<TSource, TDestination> IgnoreNoMap<TSource, TDestination>(
            this IMappingExpression<TSource, TDestination> expression)
        {
            var sourceType = typeof(TSource);
            foreach (var property in sourceType.GetProperties())
            {
                PropertyDescriptor descriptor = TypeDescriptor.GetProperties(sourceType)[property.Name];
                NoMapAttribute attribute = (NoMapAttribute)descriptor.Attributes[typeof(NoMapAttribute)];
                if (attribute != null)
                    expression.ForMember(property.Name, opt => opt.Ignore());
            }
            return expression;
        }
    }
    
    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; }
    }

    public class EmployeeDTO
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Email { get; set; }
    }
}

When we run the application, it will display the following result

Ignore Using AutoMapper in C#

In the above example, we have created a custom attribute with the name NoMap by inheriting from the Attribute class. Then we decorated the properties which need to be ignored from the source type with the newly created NoMap attribute. Within the extensions method, we just checked whether a property has this NoMap attribute or not. If the property is decorated with the NoMap attribute then we added that property to the ignored list.

In the next article, I am going to discuss the use of UseValue, ResolveUsing and Null Substitution Using AutoMapper in C# with examples. Here, in this article, I try to explain the AutoMapper Ignore Property in C# with some examples. I hope this AutoMapper Ignore Property 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 *