我想使用动态 LINQ 查询来搜索类中所有属性中的一些文本。我正在使用以下函数来创建表达式。我将属性名称和搜索文本传递给该方法。在该方法中,如果属性类型是 String,那么它工作正常。如果属性类型是 int、DateTime、GUID。然后它不工作。
我们知道 Contains 方法仅适用于元素数组或字符串。我认为属性的值应该类型转换为字符串。那么该怎么做呢?有解释的解决方案是帮助充分的。
我从这里收集了代码。
public static Expression<Func<T, bool>> ContainsExp<T>(string propertyName, string contains)
{
var parameterExp = Expression.Parameter(typeof(T), "type");
var propertyExp = Expression.Property(parameterExp, propertyName);
MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
var someValue = Expression.Constant(contains, typeof(string));
var containsMethodExp = Expression.Call(propertyExp, method, someValue);
return Expression.Lambda<Func<T, bool>>(containsMethodExp, parameterExp);
}