LINQ to Entities does not recognize the method #39;System.Object GetValue(...)#39;(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(...)"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:LINQ to Entities 无法识别方法“System.Object GetValue(...)"


- 如何用自己压缩一个 IEnumerable 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01