LINQ to Entities 无法识别方法“System.Object GetValue(...)" [英] LINQ to Entities does not recognize the method 'System.Object GetValue(...)'

查看:19
本文介绍了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时,无法理解property.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();

这篇关于LINQ to Entities 无法识别方法“System.Object GetValue(...)"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆