Converting conditionally built SQL where-clause into LINQ

℡╲_俬逩灬. 提交于 2019-12-06 07:10:19
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.

Chris Pitman

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.

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