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

后端 未结 3 1293
抹茶落季
抹茶落季 2021-01-12 03:24

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

Mapper.CreateMap

        
3条回答
  •  南笙
    南笙 (楼主)
    2021-01-12 04:21

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

    Mapper.Initialize(cfg =>
    {
        cfg.CreateMap().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();
    
        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();
            }
        });
    });
    

提交回复
热议问题