Linq to SQL 问题与 where 子句

本文关键字:where 子句 问题 to SQL Linq | 更新日期: 2023-09-27 18:33:48

我正在尝试使用以下逻辑在 Linq to SQL 中创建一个 where 子句

如果@supplierid为 null,则返回所有记录。

如果@supplierid不为空,则返回供应商 ID 等于 @supplierid。

以及造成问题的那个:

如果@supplierid ==0 则返回供应商 ID 为空的所有记录

我试着这样写这个

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

这适用于前两个条件,但当 @supplierid = 0 时,不会返回任何内容。

任何帮助将不胜感激

编辑

基本上我有一个 N/A 的下拉列表,ID 为 0。 我使用它来确定已从下拉列表中选择一个选项,并且用户正在定位供应商 ID 为 N/A 的所有行。

数据库不包含以 0 作为供应商 id 的条目,因此我尝试在 SQL 中将供应商 id 为空或以下的条目作为目标

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

Linq to SQL 问题与 where 子句

使用 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);

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

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