asp.net-mvc – LINQ to entity,错误的join类型

我有一个看起来像这样的查询….

var q = Dal.TBLINVENTORies.Where(i => i.SHOWIT);
q = q.Where(i => i.dtStart < DateTime.Now || i.dtStart == null);
q = q.Where(i => i.dtEnd > DateTime.Now || i.dtEnd == null);
q = q.Where(i => i.sSystem.Contains("OE"));
q = q.Where(i => i.WS_ActiveList_ID == 0 || i.tblWS_ActiveList.WS_MasterList_ID == 16);
var test2 = q.ToList();

紧接在“ToList()”之前,如果我检查查询,我得到以下sql(或多或少)

SELECT [Extent1].*
FROM  [dbo].[TBLINVENTORY] AS [Extent1]
INNER JOIN [dbo].[tblWS_ActiveList] AS [Extent2] ON [Extent1].[WS_ActiveList_ID] = [Extent2].[ID]
WHERE ([Extent1].[SHOWIT] = 1) 
AND (([Extent1].[dtStart] <  CAST( SysDateTime() AS datetime2)) OR ([Extent1].[dtStart] IS NULL)) 
AND (([Extent1].[dtEnd] >  CAST( SysDateTime() AS datetime2)) OR ([Extent1].[dtEnd] IS NULL)) 
AND ([Extent1].[sSystem] LIKE '%OE%') 
AND ([Extent1].[WS_ActiveList_ID] = 0  OR [Extent2].[WS_MasterList_ID] = 16)

不幸的是,这不是我需要的,因为“Inventory”和“ActiveList”之间的关系实际上并不是1对多,而是Zero-to-Many(我不确定我是否使用了正确的术语).基本上,库存项目可能有也可能没有相关的“ActiveList”.

如果我将原始SQL更改为使用LEFT OUTER JOIN而不是INNER JOIN,则SQL将返回我期望的值.

强制LEFT OUTER JOIN需要什么?

我尝试过Linq to entities – One to many relationship – need left outer join instead of cross join推荐的解决方案,但是,

var q2 =来自inv.tblWS_ActiveList中al的Dal.TBLINVENTORies中的inv

返回错误:

错误65在源类型为“System.Data.Entity.DbSet< xxxx.DAL.TBLINVENTORY>”的查询表达式的后续from子句中不允许使用类型为“xxxx.DAL.tblWS_ActiveList”的表达式.调用“SelectMany”时类型推断失败.

我想知道我的链接/关系是否构造错误?还有其他想法吗?

谢谢!

编辑::附加数据

-- create foreign key, but don't enforce on existing values
ALTER TABLE [dbo].[tblInventory]  --the ONE Table
    WITH NOCHECK 
    ADD CONSTRAINT [FK__tblInventory.WS_ActiveList_ID__tblWS_ActiveList.ID] 
        FOREIGN KEY([WS_ActiveList_ID]) 
            REFERENCES [dbo].[tblWS_ActiveList] ([ID])    --the MANY Table
        NOT FOR REPLICATION
GO

-- disable enforcement of the foreign key, but leave it in place (virtual key)
ALTER TABLE [dbo].[tblInventory]  
    NOCHECK CONSTRAINT [FK__tblInventory.WS_ActiveList_ID__tblWS_ActiveList.ID] 
GO

和WS_ActiveList_ID的定义:

[WS_ActiveList_ID] [int] NOT NULL CONSTRAINT [DF_TBLINVENTORY_WS_ActiveList_ID] DEFAULT (0),

最佳答案 您的主要问题是您已关闭数据库中的参照完整性检查.

除了明显的错误数据问题,这对EF不起作用.

到目前为止,最好的选择是使WS_ActiveList_ID可以为空,更新数据以将所有0更改为NULL并重新打开约束.

如果您不能这样做,我认为您必须生成一个SQL语句作为字符串并使用dbContext.Database.SqlQuery< T>执行它. (MSDN)

点赞