且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

automapper-如果属性类型与相同的属性名称不同,则忽略映射-C#

更新时间:2022-01-02 09:42:34

您可以使用 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();
        }
    });
});