忽略映射所有零属性,AutoMapper?

时间:2014-06-01 14:24:54

标签: c# extension-methods automapper

我想忽略AutoMapper配置中零值的所有数字属性 所以,我已经写了以下扩展方法:

public static IMappingExpression<TSource, TDestination> IgnoreZeroNumericProperties<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
    Type sourceType = typeof(TSource);
    Type destinationType = typeof(TDestination);

    List<PropertyInfo> numericPropertis = sourceType.GetProperties().ToList();
    foreach (PropertyInfo propertyInfo in numericPropertis)
    {
        string sourcePropertyName = propertyInfo.Name;
        Type sourcePropertyType = propertyInfo.PropertyType;

        if (!sourcePropertyType.IsNumericType()) continue;

        bool isTheSamePropertyExistInDestinationType = destinationType.GetProperties().Any(q => q.Name == sourcePropertyName && q.PropertyType == sourcePropertyType);
        if (!isTheSamePropertyExistInDestinationType) continue;

        ParameterExpression parameterExpression = Expression.Parameter(sourceType, "c");
        MemberExpression memberExpression = Expression.Property(parameterExpression, sourcePropertyName);
        object value = Convert.ChangeType(0, sourcePropertyType);
        ConstantExpression constantExpression = Expression.Constant(value);
        Expression<Func<TSource, bool>> lambdaExpression = Expression.Lambda<Func<TSource, bool>>(Expression.GreaterThan(memberExpression, constantExpression), parameterExpression);
        Func<TSource, bool> func = lambdaExpression.Compile();

        expression.ForMember(sourcePropertyName, opt => opt.Condition(func));
    }
    return expression;
}

我使用它如下:

Mapper.CreateMap<AttachmentModel, Attachment>().IgnoreZeroNumericProperties();

IsNumericType方法:

public static bool IsNumericType(this Type type)
{
    if (type == null)
    {
        return false;
    }

    switch (Type.GetTypeCode(type))
    {
        case TypeCode.Byte:
        case TypeCode.Decimal:
        case TypeCode.Double:
        case TypeCode.Int16:
        case TypeCode.Int32:
        case TypeCode.Int64:
        case TypeCode.SByte:
        case TypeCode.Single:
        case TypeCode.UInt16:
        case TypeCode.UInt32:
        case TypeCode.UInt64:
            return true;
        case TypeCode.Object:
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                return IsNumericType(Nullable.GetUnderlyingType(type));
            }
            return false;
    }
    return false;
}

编译没有任何问题,
但似乎没有正常工作,所有零属性都映射。 问题是什么?

1 个答案:

答案 0 :(得分:0)

我能找到问题 我已经更正了以下内容:

// q.PropertyType == sourcePropertyType removed
    bool isTheSamePropertyExistInDestinationType = destinationType.GetProperties().Any(q => q.Name == sourcePropertyName);
            if (!isTheSamePropertyExistInDestinationType) continue;

目标的属性类型为int?,源的属性类型为int。所以条件没有创造。