gpt4 book ai didi

c# - LINQ to Entities 无法识别方法 'System.Object GetValue(...)'

转载 作者:可可西里 更新时间:2023-11-01 08:37:08 27 4
gpt4 key购买 nike

我的问题是我需要查询泛型类中属性的值。该属性用属性标记。

请看下面的代码:

 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 类型。

我明白为什么我会收到错误。当 linq 查询转换为 SQL 时,它无法理解 property.GetValue。

但是,我对这里的工作完全感到困惑。有谁知道如何实现这一目标?谢谢。

最佳答案

您需要实际构建 Expression 对象来表示您希望它模仿的表达式,在这种情况下,您想要表示的表达式是:

l => l.SomeProperty == SomeValue

因此您需要一点一点地构建每个组件,从创建参数、定义相等运算符、属性访问、常量值等。

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);
}

一旦你拥有所有这些,你就可以使用你拥有的数据调用它:

var queryResult = objContext.CreateObjectSet<T>()
.Where(PropertyEquals<T, int>(tenantKeyProperty, tenantKey))
.Where(PropertyEquals<T, int>(rowKeyProperty, KeyValue))
.Single();

关于c# - LINQ to Entities 无法识别方法 'System.Object GetValue(...)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22104050/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com