gpt4 book ai didi

c# - dbcontext 和 objectcontext 中的 NULL 处理

转载 作者:太空狗 更新时间:2023-10-29 21:49:04 24 4
gpt4 key购买 nike

我有这个简单的 LINQ 查询

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

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

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;
}

关于c# - dbcontext 和 objectcontext 中的 NULL 处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37783677/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com