Dynamic where clause in Linq to Entities

前端 未结 3 2135
予麋鹿
予麋鹿 2020-12-31 11:57

I\'m using linq to entities(EF). I have a constructor which takes 4 string parameters. Depending on what parameter is not null I have to build the linq query. I can do with

3条回答
  •  再見小時候
    2020-12-31 12:44

    You could always build the query in pieces and take advantage of delayed query execution:

    public Constructor(int? p1, int? p2, int? p3, int? p4)
    {
        var prod = ctxt.products.expand("items\details");
    
        if(p1 != null)
            prod = prod.Where(p.x == p1);
    
        if(p2 != null)
            prod = prod.Where(p.xx == p2);
    
        if(p3 != null)
            prod = prod.Where(p.xxx == p3);
    
        if(p4 != null)
            prod = prod.Where(p.xxxx == p4);
    }
    

提交回复
热议问题