GorvGoyl
GorvGoyl

Reputation: 49570

automapper - ignore mapping if property type is different with same property name - C#

How can I ignore mapping if property type is different with same property name? By default it's throwing error.

Mapper.CreateMap<EntityAttribute, LeadManagementService.LeadEntityAttribute>();

Model = Mapper.Map<EntityAttribute, LeadManagementService.LeadEntityAttribute>(EntityAttribute);

I know a way to specify the property name to ignore but that's not what I want.

  .ForMember(d=>d.Field, m=>m.Ignore());

Because in the future I might add new properties. So i need to ignore mapping for all properties with different data types.

Upvotes: 8

Views: 4800

Answers (3)

haim770
haim770

Reputation: 49133

You can use ForAllMembers() to setup the appropriate mapping condition:

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<EntityAttribute, LeadEntityAttribute>().ForAllMembers(memberConf =>
    {
        memberConf.Condition((ResolutionContext cond) => cond.DestinationType == cond.SourceType);
    });
}

You can also apply it globally using ForAllMaps():

Mapper.Initialize(cfg =>
{
    // register your maps here
    cfg.CreateMap<A, B>();

    cfg.ForAllMaps((typeMap, mappingExpr) =>
    {
        var ignoredPropMaps = typeMap.GetPropertyMaps();

        foreach (var map in ignoredPropMaps)
        {
            var sourcePropInfo = map.SourceMember as PropertyInfo;
            if (sourcePropInfo == null) continue;

            if (sourcePropInfo.PropertyType != map.DestinationPropertyType)
                map.Ignore();
        }
    });
});

Upvotes: 5

Vinod
Vinod

Reputation: 1952

One way to process all properties for type is to use .ForAllMembers(opt => opt.Condition(IsValidType))). I have used new syntax for AutoMapper usage, but it should work even with old syntax.

using System;
using AutoMapper;

namespace TestAutoMapper
{
    class Program
    {
        static void Main(string[] args)
        {
            var mapperConfiguration = new MapperConfiguration(cfg => cfg.CreateMap<Car, CarDto>()
                .ForAllMembers(opt => opt.Condition(IsValidType))); //and how to conditionally ignore properties
            var car = new Car
            {
                VehicleType = new AutoType
                {
                    Code = "001DXT",
                    Name = "001 DTX"
                },
                EngineName = "RoadWarrior"
            };

            IMapper mapper = mapperConfiguration.CreateMapper();
            var carDto = mapper.Map<Car, CarDto>(car);
            Console.WriteLine(carDto.EngineName);

            Console.ReadKey();
        }

        private static bool IsValidType(ResolutionContext arg)
        {
            var isSameType = arg.SourceType== arg.DestinationType; //is source and destination type is same?
            return isSameType;
        }
    }

    public class Car
    {
        public AutoType VehicleType { get; set; } //same property name with different type
        public string EngineName { get; set; }
    }

    public class CarDto
    {
        public string VehicleType { get; set; } //same property name with different type
        public string EngineName { get; set; }
    }

    public class AutoType
    {
        public string Name { get; set; }
        public string Code { get; set; }
    }
}

Upvotes: 0

Kirill Bestemyanov
Kirill Bestemyanov

Reputation: 11964

You should use ignore for properties that should be ignored:

Mapper.CreateMap<EntityAttribute, LeadManagementService.LeadEntityAttribute>()
     ForMember(d=>d.FieldToIgnore, m=>m.Ignore());

Upvotes: 5

Related Questions