【发布时间】:2021-07-14 23:13:24
【问题描述】:
我一直在寻找解决问题的方法。所以,问题是如何过滤所有变量类型,如 int / double / decimal ...例如,我有 json 数据具有多个属性,例如 id、name、price、description ...我必须进行搜索适用于所有类型。现在,我只能查询 ("...") 字符串的字段。如何使 id/price(int / double / decimal) 成为可能?
private static Expression<Func<T, bool>> GetExpression<T>(string propertyName, string propertyValue)
{
var parametr = Expression.Parameter(typeof(T));
var property = Expression.Property(parametr, propertyName);
var containsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });
var objectContains = Expression.Constant(propertyValue, typeof(string));
var objectEquals = Expression.Equal(property, Expression.Constant(propertyValue));
var constrantMethod = Expression.Call(property, containsMethod, objectContains);
return Expression.Lambda<Func<T, bool>>(constrantMethod, parametr)
.Or(Expression.Lambda<Func<T, bool>>(objectEquals, parametr));
}
public static IQueryable<T> ApplyFiltering<T>(this IQueryable<T> source, string propertyLabel, string propertyValue)
{
if (string.IsNullOrEmpty(propertyLabel))
{
return source;
}
var propertyNames = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(property => property.PropertyType == typeof(string) && property.Name == propertyLabel)
.Select(property => property.Name);
var predicate = PredicateBuilder.New<T>();
foreach (var name in propertyNames)
{
predicate = predicate.Or(GetExpression<T>(name, propertyValue));
}
return source.Where(predicate);
}
【问题讨论】:
-
请注意,您的
ApplyFiltering没有意义,因为只有一个属性可以匹配propertyLabel,因此针对PropertyType进行测试是毫无价值的,除非您巧妙地避免了类型不匹配错误,在这种情况下您可能不应该是微妙的。
标签: c# linq entity-framework-core