LINQ to Entities无法识别方法'System.Object GetValue(...)'
我的问题是我需要查询通用类中属性的值.该属性带有属性标记.
My issue is I need to query on the value of a property in a generic class. The property is tagged with an attribute.
请参见以下代码:
var rowKeyProperty = EFUtil.GetClassPropertyForRowKey<T>();
var tenantKeyProperty = EFUtil.GetClassPropertyForTenantKey<T>();
var queryResult =
objContext.CreateObjectSet<T>().Single(l => (((int) tenantKeyProperty.GetValue(l, null)) == tenantKey) &&
(((int)rowKeyProperty.GetValue(l, null)) == KeyValue));
rowKeyProperty和tenantKeyProperty的类型为System.Reflection.PropertyInfo.
The rowKeyProperty and tenantKeyProperty are of type System.Reflection.PropertyInfo.
我了解为什么我会收到错误消息. linq查询转换为SQL时,无法理解该属性GetValue.
I understand why I am getting the error. When the linq query is translated to SQL, it can't understand the property.GetValue.
但是,我完全不了解此处的工作.有谁知道如何实现这一目标?谢谢.
However, I'm completely stumped as to a work around here. Does anyone have any ideas how to achieve this? Thx.
您实际上需要构建Expression
对象来表示您希望它模仿的表达式,在这种情况下,您想要表示的表达式是:
You need to actually build up the Expression
objects to represent the expression that you want this to mimic, in this case the expression you want to represent is:
l => l.SomeProperty == SomeValue
因此,您需要从创建参数,定义相等运算符,属性访问,常量值等一点一点地构建该组件的每个组成部分.
So you need to build up each component of that bit by bit, from creating the parameter, defining the equality operator, the property access, the constant value, etc.
public static Expression<Func<TItem, bool>> PropertyEquals<TItem, TValue>(
PropertyInfo property, TValue value)
{
var param = Expression.Parameter(typeof(TItem));
var body = Expression.Equal(Expression.Property(param, property),
Expression.Constant(value));
return Expression.Lambda<Func<TItem, bool>>(body, param);
}
一旦拥有所有这些,就可以使用所拥有的数据来调用它:
Once you have all of that you can call it using the data that you have:
var queryResult = objContext.CreateObjectSet<T>()
.Where(PropertyEquals<T, int>(tenantKeyProperty, tenantKey))
.Where(PropertyEquals<T, int>(rowKeyProperty, KeyValue))
.Single();