Linq2Sql奇怪的行为

时间:2012-04-21 07:48:20

标签: c# linq-to-sql

在我的数据库中,我有例如13个订单。

如果OrderID = 0CustomerName = "lorem"

,下面的代码会返回所有代码

如果我对该行(OrderID == 0) ?....发表评论,那就可以了。怎么了?

var result = (from x in db.Order
              where
                  (OrderID == 0) ? x.OrderID > 0 : x.OrderID == OrderID
                  &&
                  (string.IsNullOrEmpty(CustomerName)) ? 
                                            !string.IsNullOrEmpty(CustomerName)
                                            :
                                            x.User.Name.Contains(CustomerName)
              select x)
              .ToList();

1 个答案:

答案 0 :(得分:3)

我认为你不能以这种方式在LINQ查询中定义条件条件,你可以做的是,例如:

var result = (from x in db.Order where
              ((OrderID == 0 && x.OrderID > 0) ||  
                (OrderID != 0 && x.OrderID == OrderID))
                  &&
                  (string.IsNullOrEmpty(CustomerName)) ? 
                                            !string.IsNullOrEmpty(CustomerName)
                                            :
                                            x.User.Name.Contains(CustomerName)....