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 some examples. Please read our previous article before proceeding to this article where we discussed the AutoMapper Conditional Mapping in C# with some examplesBy default, the 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 in C# 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.

Let us understand AutoMapper Ignore Property in C# 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 AutoMapper Ignore Property with the Address property of the destination type 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 AutoMapper;
namespace AutoMapperDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            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 void InitializeAutomapper()
        {
            Mapper.Initialize(config =>
            {
                config.CreateMap<Employee, EmployeeDTO>()
                    //Ignoring the Address property of the destination type
                    .ForMember(dest => dest.Address, act => act.Ignore());
            });
        }
    }

    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() 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.

But, it will be a tedious procedure if you want to ignore many properties from mapping. If that is your requirement then do consider creating an extension class like the one below which will ignore the properties based on data attribute specified in the model.

Step1: Create a NoMap Attribute as shown below

Ignore Using AutoMapper in C#

Step2: Use the NoMap attribute with the source type properties which you don’t want to map with the destination type as shown in the below image.

Ignore Using AutoMapper in C#

Step3: Create an extension class as shown below which will ignore the properties which will decorate with the NoMap attribute

First import the System.ComponentModel namespace

Ignore Using AutoMapper in C#

Step4: Finally use the IgnoreNoMap method while defining the Mapping as shown below.

Ignore Using AutoMapper in C#

Below is the complete code.
using AutoMapper;
using System.ComponentModel;

namespace AutoMapperDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            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 void InitializeAutomapper()
        {
            Mapper.Initialize(config =>
            {
                config.CreateMap<Employee, EmployeeDTO>()
                      .IgnoreNoMap();
            });
        }
    }

    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, we will discuss the use of UseValue, ResolveUsing and Null Substitution Using AutoMapper in C# with examples.

SUMMARY:

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 *