Dynamic WHERE clause (OR) in LINQ to Entities
Creating dynamic queries using the OR operator in LINQ requires PredicateBuilder, a LINQKit utility. Here’s how to do it:
<code class="language-csharp">var query = from u in context.Users select u; var pred = Predicate.False<User>(); if (type.HasFlag(IdentifierType.Username)) pred = pred.Or(u => u.Username == identifier); if (type.HasFlag(IdentifierType.Windows)) pred = pred.Or(u => u.WindowsUsername == identifier); return query.Where(pred.Expand()).FirstOrDefault();</code>
However, using AsExpandable()
is another option:
<code class="language-csharp">return query.AsExpandable().Where(pred).FirstOrDefault();</code>
Expand
method allows handling of calling expressions that EF cannot handle. Without it, an exception will be thrown.
Another Predicate Builder option that achieves the same functionality without Expand
can be found at http://petemontgomery.wordpress.com/2011/02/10/a-universal-predicatebuilder/.
The above is the detailed content of How to Build a Dynamic WHERE Clause with OR in LINQ to Entities?. For more information, please follow other related articles on the PHP Chinese website!