gpt4 book ai didi

c# - 动态 Linq 属性转换为 SQL

转载 作者:太空宇宙 更新时间:2023-11-03 11:48:51 24 4
gpt4 key购买 nike

我正在尝试了解动态 linq 和表达式树。基本上是尝试做一个 equals 提供列和值作为字符串。这是我目前所拥有的

 private IQueryable<tblTest> filterTest(string column, string value)
{
TestDataContext db = new TestDataContext();

// The IQueryable data to query.
IQueryable<tblTest> queryableData = db.tblTests.AsQueryable();

// Compose the expression tree that represents the parameter to the predicate.
ParameterExpression pe = Expression.Parameter(typeof(tblTest), "item");


Expression left = Expression.Property(pe, column);
Expression right = Expression.Constant(value);
Expression e1 = Expression.Equal(left, right);

MethodCallExpression whereCallExpression = Expression.Call(
typeof(Queryable),
"Where",
new Type[] { queryableData.ElementType },
queryableData.Expression,
Expression.Lambda<Func<tblTest, bool>>(e1, new ParameterExpression[] { pe }));

// Create an executable query from the expression tree.
IQueryable<tblTest> results = queryableData.Provider.CreateQuery<tblTest>(whereCallExpression);

return results;
}

这适用于数据库中的列。但是我的代码中的属性失败,例如

public partial class tblTest
{
public string name_test
{ get { return name; } }
}

报错不能是不能转换成SQL。我曾尝试将该属性重写为 Expression

非常感谢

最佳答案

要使用非表属性,您需要先具体化查询并使用 LINQ to objects。我认为您不能同时查询 SQL 和非 SQL 属性,原因是您声明:非 SQL 属性没有 SQL 转换。我怀疑如果您在调用 filterTest() 之前执行 ToList(),您会发现您的代码对两种类型的属性都适用。不幸的是,这可能不是您想要的,如果您的非 SQL 属性派生自各种 SQL 列,您将需要一种方法来生成与属性定义匹配的表达式。

关于c# - 动态 Linq 属性转换为 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2629231/

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