2016-06-13 58 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; 
}