【问题标题】:Create linq query as string将 linq 查询创建为字符串
【发布时间】:2020-07-19 16:40:57
【问题描述】:

我有一个包含 linq 查询的字符串,并且我有一个动态 where 子句也作为包含许多动态条件的字符串 这是我的where子句

string strWhereString = "where a.id==1 && a.name==\"something\"";

这是我的 linq 查询字符串:

var query = "from a in context.tblName "+strWhereString;

问题是如何运行此查询并从表中获取结果? 有没有办法做到这一点,或者 Linq 不支持这个?

【问题讨论】:

  • Linq 查询必须在编译时强类型化,不能像 SQL 查询那样做。

标签: c# string linq


【解决方案1】:

您要查找的内容类似于 System.Linq.Dynamic

这将使您可以翻译如下查询:

var query = from p in northwind.Products
                where p.CategoryID == 3 && p.UnitPrice > 3
                orderby p.SupplierID
                select p;

进入:

var query = northwind.Products
                         .Where("CategoryID = 3 AND UnitPrice > 3")
                         .OrderBy("SupplierID");

这里也是一个很好的起点,有一篇不错的博文和一些示例可供下载。

Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library)

【讨论】:

    【解决方案2】:

    也许使用 linq 静态方法会更幸运:

    context.tblName.Where(a=>a.id==1 && a.name=="something")
    

    这种方式很容易动态添加where子句(或其他):

    context.tblName..Where(a=>a.id==1 && a.name=="something").Where(a=>otherClause(a))
    

    我不确定这是否真的是您想要的,但我认为这是正确的方向。

    【讨论】:

    • 是否可以像字符串一样向 where 子句添加条件?我的意思是这样 context.tblName.Where("some condtion")
    • 不行,需要强类型。你的用例到底是什么?
    • 我的意思是把这样的 where 子句 context.tblName..Where("SERIAL_NUMBER == xxx && MAC==xxx") 我试过了,但它不接受它
    • 我明白你的意思。但是为什么需要将子句作为字符串传递呢?
    • 因为我的子句来自过滤器之类的形式,这就是我想要这样的原因
    【解决方案3】:

    我还必须处理进行数据库搜索的动态条件。我提出了这个解决方案,而不是字符串解析或动态 LINQ。 errorsOnlystartDateendDate 可以(但不能)在前端设置。可以简单地相应地添加附加条件:

    var query = from x in db.DoubleDataValueArchive select x;
    query = query.Where(x => x.DataPointId != null);
    
    // Check if only errors should be shown (that are listed in errorDps)
    List<int> errorDps = new List<int>();
    if (errorsOnly.HasValue) {
        if (errorsOnly == true)
        {
            errorDps = db.DataPoints.Where(x => x.DataType == 4).Select(x => x.Id).ToList();
            query = query.Where(x => errorDps.Contains((int)x.DataPointId));
        }
    }
    
    // Start Date
    if (startDate.HasValue) {
        startDate = startDate.Value.ToUniversalTime();
        query = query.Where(x => x.DateValue >= startDate);
    }
    
    // End Date
    if (endDate.HasValue)
    {
        endDate = endDate.Value.ToUniversalTime();
        query = query.Where(x => x.DateValue <= endDate);
    }
    

    ...等等。这是完全动态的,但同时可以安全地使用。当您从IQueryable 中创建一个列表或类似内容时,组装的 SQL 查询只会最终执行一次。

    【讨论】:

      【解决方案4】:

      我认为您正在寻找的是动态 LINQ。这是 LINQ 团队自己提供的库。

      您需要做的是改用字符串表达式,如本博客所示 - http://weblogs.asp.net/scottgu/dynamic-linq-part-1-using-the-linq-dynamic-query-library

      【讨论】:

      • 谢谢,现在我正在使用这个库并试图从中找到解决方案。
      • @Younisbarznji 如果这回答了您的问题,那么请将其标记为答案并关闭此主题。
      猜你喜欢
      • 2011-07-05
      • 2011-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-25
      • 2011-01-04
      • 1970-01-01
      • 2014-10-28
      相关资源
      最近更新 更多