automapper – 如果属性类型与同一属性名称不同,则忽略映射 – C#
如果属性类型与同一属性名称不同,我如何忽略映射? 默认情况下,它会抛出错误。
Mapper.CreateMap(); Model = Mapper.Map(EntityAttribute);
我知道一种方法来指定要忽略的属性名称,但这不是我想要的。
.ForMember(d=>d.Field, m=>m.Ignore());
因为将来我可能会添加新属性。 所以我需要忽略具有不同数据类型的所有属性的映射。
您应该对要忽略的属性使用ignore:
Mapper.CreateMap() ForMember(d=>d.FieldToIgnore, m=>m.Ignore());
您可以使用ForAllMembers()
来设置适当的映射条件:
Mapper.Initialize(cfg => { cfg.CreateMap().ForAllMembers(memberConf => { memberConf.Condition((ResolutionContext cond) => cond.DestinationType == cond.SourceType); }); }
您也可以使用ForAllMaps()
全局应用它:
Mapper.Initialize(cfg => { // register your maps here cfg.CreateMap(); 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(); } }); });
处理类型的所有属性的一种方法是使用.ForAllMembers(opt => opt.Condition(IsValidType)))。 我已经使用了新的语法来使用AutoMapper,但它应该可以使用旧的语法。
using System; using AutoMapper; namespace TestAutoMapper { class Program { static void Main(string[] args) { var mapperConfiguration = new MapperConfiguration(cfg => cfg.CreateMap() .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); 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; } } }