dbcontext和objectcontext中的NULL处理

时间:2016-06-13 07:07:54

标签: c# entity-framework linq dbcontext 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不同?

1 个答案:

答案 0 :(得分:3)

此行为是可配置的,因此很可能是默认情况不同(我不知道默认情况不同的原因)。

控件由DbContextConfiguration.UseDatabaseNullSemantics属性提供:

  

获取或设置一个值,该值指示在比较两个操作数时是否显示数据库空语义,这两个操作数都可能为空。 默认值为false 。例如(operand1 == operand2)将被翻译为:(operand1 = operand2)如果UseDatabaseNullSemantics分别为true(((operand1 = operand2)AND(NOT(operand1 IS NULL或operand2 IS NULL)))OR((operand1 IS) NULL)AND(operand2 IS NULL)))如果UseDatabaseNullSemantics为false。

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

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