How can I ignore mapping if property type is different with same property name? By default it\'s throwing error.
Mapper.CreateMap
You should use ignore for properties that should be ignored:
Mapper.CreateMap<EntityAttribute, LeadManagementService.LeadEntityAttribute>()
ForMember(d=>d.FieldToIgnore, m=>m.Ignore());
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; }
}
}
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();
}
});
});