我正在试图为一个基于属性和值的查询添加一个'where'子句。这是我的功能的一个非常简单的版本。
Private Function simplified(ByVal query As IQueryable(Of T), ByVal PValue As Long, ByVal p As PropertyInfo) As ObjectQuery(Of T)
query = query.Where(Function(c) DirectCast(p.GetValue(c, Nothing), Long) = PValue)
Dim t = query.ToList 'this line is only for testing, and here is the error raise
Return query
End Function
错误消息是:LINQ to Entities无法识别方法'System.Object CompareObjectEqual(System.Object,System.Object,Boolean)'方法,并且此方法无法转换为商店表达式。
看起来无法在linq查询中使用GetValue。我可以通过其他方式实现这一目标吗?
在C#/ VB中发布答案。选择让你感觉更舒适的那个。
由于
编辑:我也尝试使用相同结果的代码
Private Function simplified2(ByVal query As IQueryable(Of T))
query = From q In query
Where q.GetType.GetProperty("Id").GetValue(q, Nothing).Equals(1)
Select q
Dim t = query.ToList
Return query
End Function
答案 0 :(得分:6)
您需要将代码转换为表达式树。
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace WindowsFormsApplication1
{
static class Program
{
[STAThread]
static void Main()
{
using (var context = new NorthwindEntities())
{
IQueryable<Customer> query = context.Customers;
query = Simplified<Customer>(query, "CustomerID", "ALFKI");
var list = query.ToList();
}
}
static IQueryable<T> Simplified<T>(IQueryable<T> query, string propertyName, string propertyValue)
{
PropertyInfo propertyInfo = typeof(T).GetProperty(propertyName);
return Simplified<T>(query, propertyInfo, propertyValue);
}
static IQueryable<T> Simplified<T>(IQueryable<T> query, PropertyInfo propertyInfo, string propertyValue)
{
ParameterExpression e = Expression.Parameter(typeof(T), "e");
MemberExpression m = Expression.MakeMemberAccess(e, propertyInfo);
ConstantExpression c = Expression.Constant(propertyValue, propertyValue.GetType());
BinaryExpression b = Expression.Equal(m, c);
Expression<Func<T, bool>> lambda = Expression.Lambda<Func<T, bool>>(b, e);
return query.Where(lambda);
}
}
}
答案 1 :(得分:0)
您是否尝试过取出DirectCast
并反映lambda参数?像这样:
query.Where(Function(c) _
c.GetType().GetProperty(p, GetType("Int64")).GetValue(c, Nothing) = PValue)
我不确定你甚至可以在lambda中做这类事情,但值得一试。