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

查看:70
本文介绍了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();

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

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