C# Linq-to-SQL连接允许在不使用';我不想那样
我编写了下面的查询来连接两个表。由于某些不正当的原因,la.UserProfileId可以为空 当我编写等价的SQL语句时,我得到了0条记录,正如我现在应该得到的那样C# Linq-to-SQL连接允许在不使用';我不想那样,c#,entity-framework,linq-to-sql,C#,Entity Framework,Linq To Sql,我编写了下面的查询来连接两个表。由于某些不正当的原因,la.UserProfileId可以为空 当我编写等价的SQL语句时,我得到了0条记录,正如我现在应该得到的那样 var result = (from e in _ctx.Employees join la in _ctx.LoginAudits on e.UserProfile.Id equals la.UserProfileId.Value where l
var result = (from e in _ctx.Employees
join la in _ctx.LoginAudits on e.UserProfile.Id equals la.UserProfileId.Value
where la.LoginDate >= fromDate
&& e.Client.Id == clientID
select new
{
la.Id,
employeeID = e.Id,
e.Client.DisplayName,
la.UserProfileId
}).ToList();
上面的LINQ代码生成下面的SQL
exec sp_executesql N'SELECT
1 AS [C1],
[Extent2].[Id] AS [Id],
[Extent1].[Id] AS [Id1],
[Extent3].[DisplayName] AS [DisplayName],
[Extent2].[UserProfileId] AS [UserProfileId]
FROM [dbo].[Employees] AS [Extent1]
INNER JOIN [dbo].[LoginAudits] AS [Extent2] ON ([Extent1].[UserProfile_Id] = [Extent2].[UserProfileId]) OR (([Extent1].[UserProfile_Id] IS NULL) AND ([Extent2].[UserProfileId] IS NULL))
INNER JOIN [dbo].[Clients] AS [Extent3] ON [Extent1].[Client_Id] = [Extent3].[Id]
WHERE ([Extent2].[LoginDate] >= @p__linq__0) AND ([Extent1].[Client_Id] = @p__linq__1)',N'@p__linq__0 datetime2(7),@p__linq__1 bigint',@p__linq__0='2018-02-09 11:11:29.1047249',@p__linq__1=37
如您所见,它包括“或([Extent1].[UserProfile_Id]为NULL)和([Extent2].[UserProfileId]为NULL))”
这与我想要的正好相反。如何使其进行正常的内部联接,而不尝试允许空值
我可以通过添加&&la.UserProfileId!=在我的WHERE子句中为null,但理想情况下,我宁愿让连接像普通的内部连接一样工作,而不要试图预测我不需要的东西
这与我想要的正好相反。如何使其进行正常的内部联接,而不尝试允许空值
背后的原因是,在C#null==null
中,它的计算结果为true
,而在SQL中,它的计算结果为null
(基本上处理方式类似于FALSE
)。因此EF试图模拟C#行为,以获得与在LINQ to对象中运行相同查询相同的结果
这是默认的EF6行为。它由属性控制,因此如果要使用SQL行为,应在DbContext
派生类构造函数中或从外部将其设置为true
:
[dbContext.]Configuration.UseDatabaseNullSemantics = true;
但这还不够。它影响所有比较运算符,但它们忘记将其应用于联接。解决方案是不使用LINQjoin
操作符,而是在处使用相关的(EF足够聪明,可以将其转换为SQLjoin
)
因此,除了将UseDatabaseNullSemantics
设置为true
之外,还应替换
join la in _ctx.LoginAudits on e.UserProfile.Id equals la.UserProfileId
与
您将获得所需的内部联接
模型中的字段是否可以为空?如果是,请改为尝试e.UserProfile.Id.Value?
from la in _ctx.LoginAudits where e.UserProfile.Id == la.UserProfileId