AutoMapper - Replacing Member Names

Another feature available in AutoMapper is the ability to replace characters or the complete name in the source member name while doing the mapping. This will become helpful when you deal with member names having different spelling or some special characters in it. It's normally done during the configuration for mapping and needs to do only once.

Syntax 

ReplaceMemberName("<orignial member name>","<matching property name>");

 var config = new MapperConfiguration(cfg =>
{
cfg.ReplaceMemberName("StartedOn", "Started_On");
cfg.ReplaceMemberName("Name", "FirstName");

cfg.CreateMap<ModelData, ViewModel>();
});

Here we are doing couple of replacements, one for adding a underscore to Started_On property and second one for completely using a new name for the property. One thing to note here is that you should specify the replacements before the CreateMap statement otherwise it will you invalid mapping exception at runtime.

using System;
using AutoMapper;

namespace AutoMapperSamples.Configuration
{
    namespace AutoMapperSample
    {
        
        public class ModelData
        {
            public string Name { get; set; }
            public DateTime StartedOn { get; set; }
        }



        public class ViewModel
        {
            public string FirstName { get; set; }
            public DateTime Started_On { get; set; }
        }


        public class TestAutoMapper
        {

            public static void Main()
            {
                var config = new MapperConfiguration(cfg =>
                {


                    cfg.ReplaceMemberName("StartedOn", "Started_On");
                    cfg.ReplaceMemberName("Name", "FirstName");
                    
                    cfg.CreateMap<ModelData, ViewModel>();
                });

                config.AssertConfigurationIsValid();

                var model = new ModelData { StartedOn= DateTime.Now, Name ="Amal" };

                var viewModel = config.CreateMapper().Map(model);
                Console.WriteLine("\nFirst Name " + viewModel.FirstName);
                Console.WriteLine("\nStart Date " + viewModel.Started_On);

                Console.ReadKey();
            }
        }
    }
}

And the ouptut will be

The AssertConfigurationIsValid method is used to verify all the configuration is valid or not. If it's not then an exception will thrown then there otherwise it will be thrown at the time of mapping itself. Normally we are doing the configuration during startup and it's good practice to to use this method there. Suppose if comment out the ReplaceMemberName methods in the configuration, you will get an exception like this.


No Comments

Add a Comment