automapper-如果属性类型与相同的属性名称不同,则忽略映射-C# [英] automapper - ignore mapping if property type is different with same property name - C#
本文介绍了automapper-如果属性类型与相同的属性名称不同,则忽略映射-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.
推荐答案
您可以使用 ForAllMembers( )
来设置适当的映射条件:
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);
});
}
您也可以将其全局应用使用 ForAllMaps()
:
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();
}
});
});
这篇关于automapper-如果属性类型与相同的属性名称不同,则忽略映射-C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文