【发布时间】:2021-12-30 13:46:22
【问题描述】:
我在我的 Net Core Web API 上使用 DynamicLinq。主要目的是根据OR过滤的多列选择数据
这是模型
public class Car
{
public int Id { get; set; }
public string Name { get; set; }
public string Brand { get; set; }
}
查询如下所示。 (我创建了处理所有表格的通用方法)
public static async Task<List<T>> Query<T>(this DbContext context, Dictionary<string, string> filter) where T : class
{
var query = context.Set<T>().AsQueryable();
string whereClause = "";
foreach(var d in filter)
{
if (whereClause != "")
whereClause += " || ";
whereClause += $"{d.Key}.Contains(\"{d.Value}\")";
}
return await query.Where(whereClause).ToListAsync();
}
此代码不会产生错误,但会跳过 where clause,这意味着它的执行就像没有 Where 一样,并产生了所有数据。结果查询看起来像SELECT Id, Name, Brand FROM Car,它应该像SELECT Id, Name, Brand FROM Car WHERE Name LIKE '%something%' OR Brand LIKE '%something%'
[编辑]
在运行customers.AsQueryable().Where("Name.Contains(\"David\") || Name.Contains(\"Gail\")") 时尝试这个online example 效果很好
【问题讨论】:
-
我不得不问一个显而易见的问题,字典中是否包含任何项目?
-
是的,当然有项目
-
我不知道动态 linq,但我浏览了文档,它似乎没有提到包含作为运算符。它也不是 SQL 运算符,你如何让 dynamic-linq 翻译它?
标签: c# dynamic-linq dynamic-linq-core