AutoMapper - Property/Field Filtering

By default Automapper will try to map not only public properties but also public fields found in source and destination.

using System;
using AutoMapper;

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

            public string Location;
        }



        public class ViewModel
        {
            public string Name { get; set; }
            public DateTime StartedOn { get; set; }

            public string Location;
        }


        public class TestAutoMapper
        {

            public static void Main()
            {
                var config = new MapperConfiguration(cfg =>
                {
                    cfg.CreateMap<ModelData, ViewModel>();
                });

                config.AssertConfigurationIsValid();

                var model = new ModelData { StartedOn = DateTime.Now, Name = "Bridge Construction", Location = "India" };

                var viewModel = config.CreateMapper().Map<viewmodel>(model);
                Console.WriteLine("\nName " + viewModel.Name);
                Console.WriteLine("\nStart Date " + viewModel.StartedOn);
                Console.WriteLine("\nLocation " + viewModel.Location);


                Console.ReadKey();
            }
        }
    }
}

In this example Location is a public field and it will also get mapped automatically.

Output

So if you want to ignore the fields from getting mapped, change the configuration settings as follows

var config = new MapperConfiguration(cfg =>
 {
     cfg.ShouldMapField = f => false;
     cfg.CreateMap<ModelData, ViewModel>();
 });

If you want to ignore properties then

var config = new MapperConfiguration(cfg =>
{
     cfg.ShouldMapProperty= f => false;
     cfg.CreateMap<ModelData, ViewModel>();
});

If you want include private properties in the mapping then

var config = new MapperConfiguration(cfg =>
{
    cfg.ShouldMapProperty = pi =>
       pi.GetMethod != null && (pi.GetMethod.IsPublic || pi.GetMethod.IsPrivate);

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


No Comments

Add a Comment

Recent Posts