gpt4 book ai didi

c# - 使用动态字段名称使用 LINQ 查询实体

转载 作者:行者123 更新时间:2023-11-30 19:03:39 24 4
gpt4 key购买 nike

我在 ASP.NET MVC 中创建了一个动态搜索屏幕。我通过反射从实体中检索了字段名称,这样我就可以让用户选择他们想要搜索的字段,而不是在 View 中显示所有字段。

当搜索结果回发到 Controller 时,我收到一个包含 FieldName 和 Value 的 FormCollection。我不知道正在搜索多少个字段,并且 FormCollection 仅包含用户选择的字段。

我现在希望能够在查询数据库时获取该字段名称并将其应用于我的 LINQ 语句,例如:

public List<People> SearchPeople(Dictionary<string, string> fieldValueDictionary)
{
List<People> searchResults = new List<People>();

foreach (string key in fieldValueDictionary.Keys)
{
searchResults.Add(entities.People.Where(p => p.<use the key string as the fieldName> == fieldValueDictionary[key]));
}

return searchResults;
}

在我“使用键字符串作为字段名”的地方,它就像 p => p.FirstName == fieldValueDictionary[key] where key = "FirstName"。我尝试过使用 Lambda 表达式树但失败了,并且在动态 LINQ 方面取得了一些成功。唯一的其他选择是做类似的事情:

public List<People> SearchPeople(Dictionary<string, string> fieldValueDictionary)
{
IQueryable<People> results = entities.People;

foreach (string key in fieldValueDictionary.Keys)
{
switch (k)
{
case "FirstName": results = results.Where(entities.People.Where(p => p.FirstName == k);
case "LastName": results = results.Where(entities.People.Where(p => p.LastName == k);
// Repeat for all 26 fields in table
}
}

return results.ToList<People>();
}

更新:我通过以下帖子对 Lambda 表达式树进行了研究:

dynamically create lambdas expressions + linq + OrderByDescending

Parameter problem with Expression.Lambda()

LINQ: Passing lambda expression as parameter to be executed and returned by method

我已经得到一个 lambda 来输出以下内容:“p => p.FirstName”,但我无法让它在某个地方工作。有什么建议么?我的代码如下:

MemberInfo member = typeof(People).GetProperty("FirstName");
ParameterExpression cParam = Expression.Parameter(typeof(People), "p");
Expression body = Expression.MakeMemberAccess(cParam, member);

var lambda = Expression.Lambda(body, cParam);

最佳答案

经过反复试验和搜索,我无意中发现了另一篇涵盖相同问题的 SO 帖子:

InvalidOperationException: No method 'Where' on type 'System.Linq.Queryable' is compatible with the supplied arguments

这是我修改后的有效代码:

        IQueryable query = entities.People;
Type[] exprArgTypes = { query.ElementType };

string propToWhere = "FirstName";

ParameterExpression p = Expression.Parameter(typeof(People), "p");
MemberExpression member = Expression.PropertyOrField(p, propToWhere);
LambdaExpression lambda = Expression.Lambda<Func<People, bool>>(Expression.Equal(member, Expression.Constant("Scott")), p);

MethodCallExpression methodCall = Expression.Call(typeof(Queryable), "Where", exprArgTypes, query.Expression, lambda);

IQueryable q = query.Provider.CreateQuery(methodCall);

希望通过一些非常简单的修改,我应该能够让它适用于任何类型。

再次感谢您的回答 Ani 和 John Bowen

关于c# - 使用动态字段名称使用 LINQ 查询实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3463479/

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