2011-12-02 164 views
0

我对LINQ来说很新。我有以下LINQ查询LINQ - CASE语句在WHERE子句中

var entities = context.MessagingTemplateEntities 
         .Where(m => 
          m.PartyId == partyId && 
          m.MessageTemplateTypeId == messagingTemplateTypeId && 
          m.ProductTypePartyId == productTypePartyId); 

在此查询,如果productTypePartyId是0,那么我不想把它列入& &条件。那么,如何根据值排除参数?

回答

4

不知道为什么人们总是强迫LINQ是一个衬垫。

var entities = context.MessagingTemplateEntities 
         .Where(m => 
          m.PartyId == partyId && 
          m.MessageTemplateTypeId == messagingTemplateTypeId); 

if(productTypePartyId != 0) 
    entities = entites.Where(m.ProductTypePartyId == productTypePartyId); 

为自己决定哪一个更容易阅读一目了然。

2

使用&& (m.ProductTypePartyId == productTypePartyId || productTypePartyId == 0) 而不是&& m.ProductTypePartyId == productTypePartyId

+0

当productTypePartyId为0时它将不起作用,它将被添加到AND条件中,并且由于productTypePartyId = 0的表中没有记录,它将返回空实体。 – pramodtech

+0

对不起,错字。编辑我的答案 - 从第二个子句删除'm.'。 –

+1

还需要正确套管.. –

2
var entities = context.MessagingTemplateEntities 
         .Where(m => 
          m.PartyId == partyId && 
          m.MessageTemplateTypeId == messagingTemplateTypeId && 
          (productTypePartyId == 0 ? 
           true : 
           m.ProductTypePartyId == productTypePartyId));