【发布时间】:2012-02-02 09:24:40
【问题描述】:
我必须遵循以下代码:
private static bool DoesColValueExist<T>(IQueryable dataToSearchIn, string colName, string colValue)
{
int noOfClients = 1;
Type type = typeof(T);
if (colValue != "" && colName != "")
{
var property = type.GetProperty(colName);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
Expression left = Expression.Call(propertyAccess, typeof(object).GetMethod("ToString", System.Type.EmptyTypes));
left = Expression.Call(left, typeof(string).GetMethod("ToLower", System.Type.EmptyTypes));
Expression right = Expression.Constant(colValue.ToLower(), typeof(string));
MethodInfo method = typeof(string).GetMethod("Equals", new[] { typeof(string) });
Expression searchExpression = Expression.Call(left, method, right);
MethodCallExpression whereCallExpression = Expression.Call(
typeof(Queryable),
"Where",
new Type[] { type },
dataToSearchIn.Expression,
Expression.Lambda<Func<T, bool>>(searchExpression, new ParameterExpression[] { parameter }));
var searchedData = dataToSearchIn.Provider.CreateQuery(whereCallExpression);
noOfClients = searchedData.Cast<T>().Count();
if (noOfClients == 0)
return false;
else
return true;
}
return true;
}
它适用于 LINQ to SQL,但使用 LINQ to Entities,我收到错误:
LINQ to Entities 无法识别方法“System.String ToString()”方法,并且该方法无法转换为存储表达式。
【问题讨论】:
-
列的类型有哪些?它们不是字符串吗?为什么不将
colValue转换为适当的类型然后进行比较呢? L2E 支持的操作受设计限制。 -
只是略过这个问题,我想知道您是否想查看 LINQKit 中的 DynamicQuery 或 PredicateBuilder - 前者@weblogs.asp.net/scottgu/archive/2008/01/07/… 和后者@albahari.com/nutshell/linqkit.aspx
标签: c# linq linq-to-entities expression-trees