Dynamic where clause (OR) in Linq to Entities

前端 未结 2 1871
独厮守ぢ
独厮守ぢ 2020-11-22 13:41

In the post here I learned how to build a dynamic query using the deferred execution of Linq. But the query is actually using an AND concatenation of the WH

相关标签:
2条回答
  • 2020-11-22 13:55

    This should help..

    Contains Query on multiple columns

    It also appears that there is a fundamental problem in the table design (Please correct me if I am wrong). What is the purpose of the IdentifierType in your database?

    0 讨论(0)
  • 2020-11-22 14:02

    With LINQKit's PredicateBuilder you can build predicates dynamically.

    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();
    // or return query.AsExpandable().Where(pred).FirstOrDefault();
    

    This is what the Expand is for:

    Entity Framework's query processing pipeline cannot handle invocation expressions, which is why you need to call AsExpandable on the first object in the query. By calling AsExpandable, you activate LINQKit's expression visitor class which substitutes invocation expressions with simpler constructs that Entity Framework can understand.

    Or: without it an expression is Invoked, which causes an exception in EF:

    The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.

    Later addition:

    There is an alternative predicate builder that does the same but without Expand: http://petemontgomery.wordpress.com/2011/02/10/a-universal-predicatebuilder/

    0 讨论(0)
提交回复
热议问题