views:

182

answers:

3

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";
        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.

A: 

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

You may also be interested in this PredicateBuilder.

Dave Swersky
A: 

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.

Chris
+2  A: 
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;
}
Remus Rusanu
That's exactly what I want, thanks
ZombieDev