2016-06-13 59 views
6

我有这个简单的LINQ查询NULL处理中的DbContext和ObjectContext的

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处理空值与dbcontext不同?

回答

3

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

的控制由DbContextConfiguration.UseDatabaseNullSemantics属性提供:

获取或设置指示是否比较两个操作数,这两者都是潜在可空时数据库null语义展出的值。 默认值为假。例如,如果UseDatabaseNullSemantics为真(((操作数1 =操作数2)AND(不是(操作数1 IS NULL或操作数2 IS NULL)))OR((操作数1操作数2)将被翻译为(操作数1 =操作数2) NULL)AND(operand2 IS NULL)))如果UseDatabaseNullSemantics为false。

要获得相同的翻译在你的第一个例子,你应该把它设置为true(例如你的数据库上下文构造内):

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