gpt4 book ai didi

vb.net - 帮助使用 Linq 和泛型。在查询中使用 GetValue

转载 作者:行者123 更新时间:2023-12-01 10:11:37 25 4
gpt4 key购买 nike

我正在尝试创建一个函数,该函数将一个“where”子句添加到基于属性和值的查询中。这是我的函数的一个非常简单的版本。

Private Function simplified(ByVal query As IQueryable(Of T), ByVal PValue As Long, ByVal p As PropertyInfo) As ObjectQuery(Of T)

query = query.Where(Function(c) DirectCast(p.GetValue(c, Nothing), Long) = PValue)
Dim t = query.ToList 'this line is only for testing, and here is the error raise
Return query

End Function

错误消息是:LINQ to Entities 无法识别方法 'System.Object CompareObjectEqual(System.Object, System.Object, Boolean)' 方法,并且此方法无法转换为存储表达式。

看起来不能在 linq 查询中使用 GetValue。我可以通过其他方式实现这一目标吗?

在 C#/VB 中发布您的答案。选择让您感觉更舒适的那一款。

谢谢

编辑 : 我也试过这个代码,结果相同
Private Function simplified2(ByVal query As IQueryable(Of T))

query = From q In query
Where q.GetType.GetProperty("Id").GetValue(q, Nothing).Equals(1)
Select q
Dim t = query.ToList
Return query
End Function

最佳答案

您需要将代码转换为表达式树。

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace WindowsFormsApplication1
{
static class Program
{
[STAThread]
static void Main()
{
using (var context = new NorthwindEntities())
{
IQueryable<Customer> query = context.Customers;
query = Simplified<Customer>(query, "CustomerID", "ALFKI");
var list = query.ToList();
}
}

static IQueryable<T> Simplified<T>(IQueryable<T> query, string propertyName, string propertyValue)
{
PropertyInfo propertyInfo = typeof(T).GetProperty(propertyName);
return Simplified<T>(query, propertyInfo, propertyValue);
}

static IQueryable<T> Simplified<T>(IQueryable<T> query, PropertyInfo propertyInfo, string propertyValue)
{
ParameterExpression e = Expression.Parameter(typeof(T), "e");
MemberExpression m = Expression.MakeMemberAccess(e, propertyInfo);
ConstantExpression c = Expression.Constant(propertyValue, propertyValue.GetType());
BinaryExpression b = Expression.Equal(m, c);

Expression<Func<T, bool>> lambda = Expression.Lambda<Func<T, bool>>(b, e);
return query.Where(lambda);
}
}
}

关于vb.net - 帮助使用 Linq 和泛型。在查询中使用 GetValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4546463/

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