Converting conditionally built SQL where-clause into LINQ

落花浮王杯 提交于 2019-12-22 17:55:40

问题


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.


回答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:


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

You may also be interested in this PredicateBuilder.




回答3:


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.



来源:https://stackoverflow.com/questions/1849005/converting-conditionally-built-sql-where-clause-into-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!