【问题标题】:Dynamic LINQ or multiple columns动态 LINQ 或多列
【发布时间】: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


【解决方案1】:

我在 Dotnet 5 和 Dotnet 6 中测试了您的通用方法。一切正常。如果您使用最新版本的 Dotnet & EfCore & Dynamic LINQ,我认为您的问题可以解决。

【讨论】:

  • 这应该是评论而不是答案
猜你喜欢
  • 2011-04-25
  • 1970-01-01
  • 2012-04-18
  • 2014-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-04
相关资源
最近更新 更多