AutoMapper Conditional Mapping in C#

AutoMapper Conditional Mapping in C# with Examples

In this article, I am going to discuss the AutoMapper Conditional Mapping in C# with examples. Please read our previous article where we discussed the Reverse Mapping Using AutoMapper in C# with examples. At the end of this article, you will understand what is AutoMapper Conditional Mapping and when and how to use conditional mapping in C#.

What is AutoMapper Conditional Mapping?

The AutoMapper in C# allows us to add conditions to the properties of the source object that must be met before that property going to be mapped to the property of the destination object.  For example, if we want to map a property only if its value is greater than 0, then in such a situation we need to use C# AutoMapper Conditional Mapping

Example to understand Conditional Mapping in AutoMapper

Let us understand Conditional Mapping using automapper with an example. We are going to use the following two classes in this demo.

AutoMapper Conditional Mapping in C#

Business Requirement:
  1. We need to Map the Name property of the Product class to the itemName property of the ProductDTO class only if the Name value starts with the letter “A”, else Map the OptionalName property value of the Product class with the ItemName property of the ProductDTO class.
  2. If the Quantity value is greater than 0 then only map it to the ItemQuantity
  3. Similarly, if the Amount value is greater than 100 then only map it to the Amount property of the ProductDTO class.

To achieve this we need to use the AutoMapper Conditional Mapping. So Initializes the Mapper configuration as shown below to use the C# AutoMapper Conditional Mapping.

What is AutoMapper Conditional Mapping

 

The Condition option in AutoMapper is used to add conditions to the properties that must be met before that property is going to map. The MapFrom option is used to perform the custom source and destination member mappings.

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

            Product product = new Product()
            {
                ProductID = 101,
                Name = "Led TV",
                OptionalName = "Product name not start with A",
                Quantity = -5,
                Amount = 1000
            };

            var productDTO = mapper.Map<Product, ProductDTO>(product);
            
            Console.WriteLine("After Mapping : Product");
            Console.WriteLine("ProductID : " + product.ProductID);
            Console.WriteLine("Name : " + product.Name);
            Console.WriteLine("OptionalName : " + product.OptionalName);
            Console.WriteLine("Quantity : " + product.Quantity);
            Console.WriteLine("Amount : " + product.Amount);
            Console.WriteLine();

            Console.WriteLine("After Mapping : ProductDTO");
            Console.WriteLine("ProductID : " + productDTO.ProductID);
            Console.WriteLine("ItemName : " + productDTO.ItemName);
            Console.WriteLine("ItemQuantity : " + productDTO.ItemQuantity);
            Console.WriteLine("Amount : " + productDTO.Amount);

            Console.ReadLine();
        }
        
        static Mapper InitializeAutomapper()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Product, ProductDTO>()

                    //If the Name Start with A then Map the Name Value else Map the OptionalName value
                    .ForMember(dest => dest.ItemName, act => act.MapFrom(src =>
                        (src.Name.StartsWith("A") ? src.Name : src.OptionalName)))

                    //Take the quantity value if its greater than 0
                    .ForMember(dest => dest.ItemQuantity, act => act.Condition(src => (src.Quantity > 0)))

                    //Take the amount value if its greater than 100
                    .ForMember(dest => dest.Amount, act => act.Condition(src => (src.Amount > 100)));
            });

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

    public class Product
    {
        public int ProductID { get; set; }
        public string Name { get; set; }
        public string OptionalName { get; set; }
        public int Quantity { get; set; }
        public int Amount { get; set; }
    }
    public class ProductDTO
    {
        public int ProductID { get; set; }
        public string ItemName { get; set; }
        public int ItemQuantity { get; set; }
        public int Amount { get; set; }
    }
}
When you run the application, it displays the following output

AutoMapper Conditional Mapping in C# with examples

Note: The C# AutoMapper Conditional Mapping is one of the important concepts of Automapper which is used in most of the real-time projects.

In the next article, I am going to discuss how to use the AutoMapper Ignore Property in C#. Here, in this article, I try to explain AutoMapper Conditional Mapping in C# with some examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

4 thoughts on “AutoMapper Conditional Mapping in C#”

  1. what do default values get destination member if conditions are not met? the destination member can be a type of string, short, bool

  2. Hi sir,

    The below mapping is not working.(IF quantity greater than 0 not working)
    .ForMember(dest => dest.ItemQuantity, act => act.Condition(src => (src.Quantity > 0)))
    I think this has to be modified to include act.MapFrom() as well.
    Can you please check this once?

  3. It is working sir..after adding the below conditions in the configuration section.
    .ForMember(dest => dest.ItemQuantity, act => act.MapFrom(src=>src.Quantity)) .ForMember(dest=>dest.ItemQuantity,act=>act.Condition(src=>(src.Quantity>0)))

Leave a Reply

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