【问题标题】:How to build up a Linq to Sql where clause bit by bit?如何一点一点地构建一个 Linq to Sql where 子句?
【发布时间】:2009-05-22 23:30:52
【问题描述】:

我在参数类中传递了一组查询字符串参数,用于查询图像数据库。每次调用时,一些参数可能为空。所以在 sql 中我会建立这样的查询

if (parameters.Value1 != null)
{
    sql.Append("sql_where_clause");
}

if (parameters.Value2 != null)
{
    sql.Append("sql_where_clause");
}

我如何使用 Linq 做同样的事情?

【问题讨论】:

    标签: c# linq-to-sql


    【解决方案1】:

    动态构建 where 子句的最佳方式是使用出色的 Albahari PredicateBuilder

    您可以使用它来构建包含ORAND 的where 子句表达式。最初打算为此提供语言集成支持,但 didn't quite make 将其纳入 C# 3。

    例如:

    var whereClause = PredicateBuilder.False<Customer>();
    
    if (parameters.Value1 != null)
    {
        whereClause = whereClause.Or(customer => customer.City == parameters.Value1);
    }
    
    var query = db.Customers.Where(whereClause);
    

    【讨论】:

    • 这成就/拯救了我的一天。谢谢。而且我在想我只是没有让 Linq 到 sql,因为我刚开始使用它..但是可惜上面到 PredicateBuilder 的链接很棒! :) 这绝对是应该存在的东西??
    【解决方案2】:

    很简单,IQueryable 在您枚举之前不会被评估,所以只需继续标记 where 子句。

    if (parameters.Value1 != null)
    {
        results = results.Where(x => <some condition>);
    }
    
    if (parameters.Value2 != null)
    {
        results = results.Where(x => <some other condition>);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-06
      • 2015-08-29
      • 1970-01-01
      • 1970-01-01
      • 2016-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多