忽略映射所有零属性,AutoMapper
本文关键字:属性 AutoMapper 映射 | 更新日期: 2023-09-27 18:06:04
我想忽略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;
}
编译没有任何问题,
但它似乎不能正常工作,所有零属性映射。有什么问题?
我能找到问题。
我更正了以下行:
// q.PropertyType == sourcePropertyType removed
bool isTheSamePropertyExistInDestinationType = destinationType.GetProperties().Any(q => q.Name == sourcePropertyName);
if (!isTheSamePropertyExistInDestinationType) continue;
目的属性类型为int?
,源属性类型为int
。所以条件没有创建