Automapper - ignore display if property type is different with the same property name - C #

How to ignore matching if the property type is different from the same property name? By default, it throws an error.

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

I know a way to specify a property name to ignore, but that is not what I want.

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

Because in the future I can add new properties. Therefore, I need to ignore matching for all properties with different data types.

+6
source share
3 answers

You should use ignore for properties that should be ignored:

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

You can use ForAllMembers() to configure the appropriate matching 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(); } }); }); 
+3
source

One way to handle all the properties for a type is to use .ForAllMembers (opt => opt.Condition (IsValidType))). I used the new syntax to use AutoMapper, but it should work even with the 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; } } } 
0
source

All Articles