Linq2Sql 奇怪的行为

本文关键字:Linq2Sql | 更新日期: 2023-09-27 18:32:00

在我的数据库中,我有例如 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();

Linq2Sql 奇怪的行为

我认为您不能以这种方式在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)....