Dynamic where clause in Linq to Entities

前端 未结 3 2150
予麋鹿
予麋鹿 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:32

    You can chain the methods as needed:

     YourType(string p1, string p2, string p3, string p4)
     {
          var prod = ctxt.Products.Expand("items\details");
    
          if (!p1.IsNullOrWhiteSpace())
              prod = prod.Where(p => p.x == p1);
          if (!p2.IsNullOrWhiteSpace())
              prod = prod.Where(p => p.xx == p2);
    
          // ....
    
          // use "prod"
     }
    

    The resulting SQL should be the same as if you put them all in a single statement.

提交回复
热议问题