简体   繁体   English

dbcontext和objectcontext中的NULL处理

[英]NULL handling in dbcontext and objectcontext

I have this simple LINQ query 我有这个简单的LINQ查询

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

Here DesignationID is a nullable field: 这里的DesignationID是一个可以为空的字段:

In objectcontext the query is translated to: 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]

While the same query in dbcontext it is translated to: 虽然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))

Why does objectcontext handle NULL differently than dbcontext ? 为什么objectcontext不同于dbcontext处理NULL?

This behavior is configurable, so most likely it's a matter of a different default (I don't know why the default is different). 这种行为是可配置的,所以很可能是一个不同的默认值(我不知道为什么默认值不同)。

The control is provided by the DbContextConfiguration.UseDatabaseNullSemantics property: 该控件由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 . 默认值为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. 例如(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。

To get the same translation as in your first example, you should set it to true (for instance inside your db context constructor): 要获得与第一个示例中相同的转换,应将其设置为true (例如,在db上下文构造函数中):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM