开发者

Converting conditionally built SQL where-clause into LINQ

开发者 https://www.devze.com 2022-12-13 11:33 出处:网络
So I didn\'t see a question here that really answers this question. It\'s kinda a newbie question about linq but I would like to know if it would be possible to convert the following sql query (built

So I didn't see a question here that really answers this question. It's kinda a newbie question about linq but I would like to know if it would be possible to convert the following sql query (built using C#) into a linq query:

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

    if (whereCriteria1)
    {
        fromClause += ", address a";开发者_C百科
        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
}

Does that make sense? I have a bunch of bool variables that let me know which where clause criteria to add. I want to do that in linq because well ... this is ugly.


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;
}


You're looking for dynamic predicates built at runtime. Here is a good CodeProject article.

You may also be interested in this PredicateBuilder.


Sure, the answer is similar to the one I provided for this question. The basic strategy is to define your "base query" and then to conditionally add where clauses to the query.

0

精彩评论

暂无评论...
验证码 换一张
取 消