强制linq执行内连接

Mag*_*pie 10 c# sql linq linq-to-sql

我试图迫使Linq在两个表之间进行内连接.我举个例子.

CREATE TABLE [dbo].[People] (
   [PersonId] [int] NOT NULL,
   [Name] [nvarchar](MAX) NOT NULL,
   [UpdatedDate] [smalldatetime] NOT NULL
   ... Other fields ...
)

CREATE TABLE [dbo].[CompanyPositions] (
   [CompanyPositionId] [int] NOT NULL,
   [CompanyId] [int] NOT NULL,
   [PersonId] [int] NOT NULL,
   ... Other fields ...
)
Run Code Online (Sandbox Code Playgroud)

现在我正在使用不寻常的数据库,因为有一个我无法控制的原因,人们在People表中丢失但在CompanyPositions中有记录.我想通过加入表来过滤掉缺少人员的CompanyPositions.

return (from pos in CompanyPositions
        join p in People on pos.PersonId equals p.PersonId
        select pos).ToList();
Run Code Online (Sandbox Code Playgroud)

Linq认为此连接是冗余的,并将其从它生成的SQL中删除.

SELECT 
[Extent1].[CompanyPositionId] AS [CompanyPositionId], 
[Extent1].[CompanyId] AS [CompanyId], 
.... 
FROM  [dbo].[CompanyPositions] AS [Extent1]
Run Code Online (Sandbox Code Playgroud)

然而,在我的情况下,这并不是多余的.我可以像这样解决它

// The min date check will always be true, here to force linq to perform the inner join
var minDate = DateTimeExtensions.SqlMinSmallDate;

return (from pos in CompanyPositions
        join p in People on pos.PersonId equals p.PersonId
        where p.UpdatedDate >= minDate
        select pos).ToList();
Run Code Online (Sandbox Code Playgroud)

但是现在这在我的SQL中创建了一个不必要的where子句.作为一个最纯粹的我想删除它.任何想法或当前的数据库设计是否与我联系?

Ral*_*ton 3

由于 PersonId 已声明NOT NULL(我假设它已声明为 People 的 FK),那么我不确定如何与未分配的人员拥有 CompanyPosition;并且 Linq 无法看到您如何能够这样做,这就是为什么正如您所观察到的,Linq 认为连接是多余的。