Linq to SQL where 子句的问题

Linq to SQL issue with where clause

我正在尝试使用以下逻辑

在 Linq 中创建一个 where 子句到 SQL

如果@supplierid 为空 return 所有记录。

如果@supplierid 不为空 return 其中 supplierid 等于 @supplierid。

以及制造问题的人:

if @supplierid ==0 return supplierid 为空的所有记录

我试过这样写

var answers =
            from thisChargeableService in this.GetAll()
            where
            (
                (
                    (supplierId == null) ||
                    (
                        ((supplierId < 1) && (thisChargeableService.SupplierId == null)) ||
                        ((supplierId != null) && (thisChargeableService.SupplierId == supplierId.Value))
                    )
                ));

这适用于前两个条件,但当@supplierid = 0 时,return 什么都没有。

如有任何帮助,我们将不胜感激

编辑

基本上我有一个 id 为 0 的 N/A 下拉列表。我用它来识别已从下拉列表中选择了一个选项,并且用户正在定位供应商 id 为 N/A.

数据库不包含 supplierid 为 0 的条目,因此我试图将其定位为 supplierid 为 null 或以下 SQL

    SELECT * FROM ChargeableService
WHERE 
(@supplierid is null)
OR
(
(@supplierid is not null and supplierid = @supplierid) or
(@supplierid = 0 AND supplierid is null)
)

我已经接受了你的查询,运行 它针对一些类似的数据和以下工作:

var answers =
        from thisChargeableService in this.GetAll()
        where
        (
            supplierId == null ||
            (supplierId == 0 && thisChargeableService.SupplierId == null) ||
            (supplierId > 0 && thisChargeableService.SupplierId == supplierId)
        )
        select thisChargeableService;

使用 Linq,无需尝试构建一个查询来完成所有工作。相反,您可以在 buts 中构建表达式,让延迟执行构建并执行正确的 sql.

所以,这就是我要做的方式。

  var answers =  this.GetAll().AsQueryable();

  if (supplierId.HasValue && (supplierId.Value != 0))
     answers = answers.Where(a=>a.SupplierId == supplierId.Value);

  if (supplierId.HasValue && (supplierId.Value == 0))
     answers = answers.Where(a=>!a.SupplierId.HasValue);