我有一个看起来像这样的查询......
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”之间的关系并不是真正的一对多,而是零对多(我不确定我使用的术语是否正确)。基本上,库存项目可能有也可能没有相关的“ActiveList”。
如果我将原始 SQL 更改为使用 aLEFT OUTER JOIN
而不是a INNER JOIN
,则 SQL 返回我期望的值。
需要什么来强制 LEFT OUTER JOIN?
我已经尝试过从 Linq 到实体的推荐解决方案 - 一对多关系 - 需要 left outer join 而不是 cross join,但是,
var q2 = from inv in Dal.TBLINVENTORies from al in inv.tblWS_ActiveList
返回错误:
Error 65 An expression of type 'xxxx.DAL.tblWS_ActiveList' is not allowed in a subsequent from clause in a query expression with source type 'System.Data.Entity.DbSet<xxxx.DAL.TBLINVENTORY>'. Type inference failed in the call to '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),