<column> IS NULL vs <column> = LINQ to SQL生成的SQL </column> </column>中的NULL

时间:2010-09-15 00:05:41

标签: sql-server-2005 linq-to-sql null

ASP.NET MVC 2.0中的

我正在做类似下面的事情(具体来说,根据某些值匹配记录以及一些NULL值)。

var result = dataContext.Inventory
 .SingleOrDefault(x => (x.part_id == model.Part.id &&
                        x.location_id == transaction.to_location_id &&
                        x.bin_id == transaction.to_bin_id &&
                        x.project_id == transaction.project_id &&
                        x.expiration_date == inventoryToTransfer.expiration_date));

...返回null。我知道记录存在,但生成的SQL(如果我打开SQL登录)是

SELECT [t0].[id], [t0].[part_id], etc...
FROM [dbo].[Inventory] AS [t0]
INNER JOIN [dbo].[Parts] AS [t1] ON [t1].[id] = [t0].[part_id]
WHERE ([t0].[part_id] = @p0) AND (([t0].[location_id]) = @p1) AND ([t0].[bin_id] = @p2) AND
([t0].[project_id] = @p3) AND ([t0].[expiration_date] = @p4)
-- @p0: Input BigInt (Size = 0; Prec = 0; Scale = 0) [5197]
-- @p1: Input BigInt (Size = 0; Prec = 0; Scale = 0) [57]
-- @p2: Input BigInt (Size = 0; Prec = 0; Scale = 0) [71]
-- @p3: Input BigInt (Size = 0; Prec = 0; Scale = 0) [Null]
-- @p4: Input DateTime (Size = 0; Prec = 0; Scale = 0) [Null]

实际上它将返回什么,因为= NULL的比较将返回无匹配。我在想的是,这将产生IS NULL(效果很好)。像这样......

...
([t0].[project_id] IS NULL) AND ([t0].[expiration_date] IS NULL)

我对此缺少什么?我相信我可以在SQL Server中打开ANSI_NULLS,但这已被弃用,必须有一种更简单的方法。

我知道,我知道......我不应该用NULL值来定义唯一性,但有没有解决方法呢?

1 个答案:

答案 0 :(得分:3)

使用object.equals来帮助确保查询返回为空

http://www.brentlamborn.com/post/LINQ-to-SQL-Null-check-in-Where-Clause.aspx

将可以为空的项目的位置更改为((variable == null && x.column == null) || (x.column == variable))

http://blog.linqexchange.com/index.php/how-to-use-is-null-with-linq-to-sql/