【问题标题】:Converting conditionally built SQL where-clause into LINQ将有条件构建的 SQL where 子句转换为 LINQ
【发布时间】:2010-12-23 08:52:13
【问题描述】:

所以我在这里没有看到真正回答这个问题的问题。这是一个关于 linq 的新手问题,但我想知道是否可以将以下 sql 查询(使用 C# 构建)转换为 linq 查询:

public void DoSomeQuery(bool whereCriteria1, bool whereCriteria2)
{
    string sqlQuery = "SELECT p.*";
    string fromClause = " FROM person p";
    string whereClause = " WHERE ";

    if (whereCriteria1)
    {
        fromClause += ", address a";
        whereClause += " p.addressid = a.addressid and a.state = 'PA' and a.zip = '16127' "
    }

    if (whereCriteria2)
    {
        fromClause += ", color c";
        whereClause += " p.favoritecolorid = c.colorid and c.name = 'blue'"
    }

    // arbitrarily many more criteria if blocks could be here

    sqlQuery += fromClause + whereClause;

    // do stuff to run the query
}

这有意义吗?我有一堆布尔变量,它们让我知道要添加哪个 where 子句标准。我想在 linq 中这样做,因为好吧……这很丑。

【问题讨论】:

    标签: c# linq linq-to-sql conditional where-clause


    【解决方案1】:
    var query = from p in persons select p;
    if (whereCriteria1)
    {
      query = from p in query 
      join a in address on p.addressid equals a.addressid 
      where a.state = 'PA' 
      where a.zip = '16127'
      select p;
    }
    if (whereCriteria2)
    {
      query = from p in query
      join c in colors on p.favoritecolorid equals c.colorid 
      where c.name = 'blue'
      select p;
    }
    

    【讨论】:

      【解决方案2】:

      当然,答案类似于我为this question 提供的答案。基本策略是定义您的“基本查询”,然后有条件地将 where 子句添加到查询中。

      【讨论】:

        【解决方案3】:

        您正在寻找在运行时构建的动态谓词。 Here 是一篇很好的 CodeProject 文章。

        您可能也对此PredicateBuilder感兴趣。

        【讨论】:

        • 很棒的文章(PredicateBuilder)——这完全解决了我的问题。谢谢!如果可以的话 +10...
        猜你喜欢
        • 1970-01-01
        • 2015-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-30
        • 2011-08-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多