dbcontext 和 objectcontext 中的 NULL 处理

NULL handling in dbcontext and objectcontext

我有这个简单的 LINQ 查询

from e in Employees 
where e.DesignationID !=558
select e

这里DesignationID是一个可为空的字段:

objectcontext 中,查询被翻译成:

SELECT 
[Extent1].[EmployeeID] AS [EmployeeID], 
[Extent1].[EmployeeCode] AS [EmployeeCode], 
[Extent1].[EmployeeName] AS [EmployeeName],
[Extent1].[DesignationID] AS [DesignationID] 
FROM [dbo].[setupEmployees] AS [Extent1]
WHERE 558 <> [Extent1].[DesignationID]

虽然 dbcontext 中的相同查询被翻译为:

 SELECT 
    [Extent1].[EmployeeID] AS [EmployeeID], 
    [Extent1].[EmployeeCode] AS [EmployeeCode], 
    [Extent1].[EmployeeName] AS [EmployeeName],
    [Extent1].[DesignationID] AS [DesignationID] 
    FROM [dbo].[setupEmployees] AS [Extent1]
 WHERE  NOT ((558 = [Extent1].[DesignationID]) AND ([Extent1].[DesignationID] IS NOT NULL))

为什么 objectcontext 处理 NULL 的方式与 dbcontext 不同?

此行为是可配置的,所以很可能是不同的默认设置(我不知道为什么默认设置不同)。

控件由 DbContextConfiguration.UseDatabaseNullSemantics 属性:

提供

Gets or sets a value indicating whether database null semantics are exhibited when comparing two operands, both of which are potentially nullable. The default value is false. For example (operand1 == operand2) will be translated as: (operand1 = operand2) if UseDatabaseNullSemantics is true, respectively (((operand1 = operand2) AND (NOT (operand1 IS NULL OR operand2 IS NULL))) OR ((operand1 IS NULL) AND (operand2 IS NULL))) if UseDatabaseNullSemantics is false.

要获得与第一个示例相同的翻译,您应该将其设置为 true(例如在您的数据库上下文构造函数中):

public YourDbContext()
{
    // ...
    this.Configuration.UseDatabaseNullSemantics = true;
}