我有一個LinqToEntities查詢,在創建SQL時會產生一個子查詢。這會導致結果集返回0-3結果,每次查詢運行。子查詢本身會產生一個隨機結果(因爲它應該)。這裏發生了什麼?LinqToEntities生成不正確的SQL(加倍子查詢)
LINQ查詢:
from jpj in JobProviderJobs
where jpj.JobID == 4725
&& jpj.JobProviderID == (from jp2 in JobProviderJobs
where jp2.JobID == 4725
orderby Guid.NewGuid()
select jp2.JobProviderID).FirstOrDefault()
select new
{
JobProviderID = jpj.JobProviderID
}
產生這種SQL:
SELECT
[Filter2].[JobID] AS [JobID],
[Filter2].[JobProviderID1] AS [JobProviderID]
FROM (SELECT [Extent1].[JobID] AS [JobID], [Extent1].[JobProviderID] AS [JobProviderID1], [Limit1].[JobProviderID] AS [JobProviderID2]
FROM [dbo].[JobProviderJob] AS [Extent1]
LEFT OUTER JOIN (SELECT TOP (1) [Project1].[JobProviderID] AS [JobProviderID]
FROM (SELECT
NEWID() AS [C1],
[Extent2].[JobProviderID] AS [JobProviderID]
FROM [dbo].[JobProviderJob] AS [Extent2]
WHERE 4725 = [Extent2].[JobID]
) AS [Project1]
ORDER BY [Project1].[C1] ASC) AS [Limit1] ON 1 = 1
WHERE 4725 = [Extent1].[JobID]) AS [Filter2]
LEFT OUTER JOIN (SELECT TOP (1) [Project2].[JobProviderID] AS [JobProviderID]
FROM (SELECT
NEWID() AS [C1],
[Extent3].[JobProviderID] AS [JobProviderID]
FROM [dbo].[JobProviderJob] AS [Extent3]
WHERE 4725 = [Extent3].[JobID]
) AS [Project2]
ORDER BY [Project2].[C1] ASC) AS [Limit2] ON 1 = 1
WHERE [Filter2].[JobProviderID1] = (CASE WHEN ([Filter2].[JobProviderID2] IS NULL) THEN 0 ELSE [Limit2].[JobProviderID] END)
編輯:
因此改變子查詢到這個工作,但我不知道爲什麼
(from jp2 in JobProviderJobs
where jp2.JobID == 4725
orderby Guid.NewGuid()
select jp2).FirstOrDefault().JobProviderID
希望我能加3,完美的答案:行爲,解決方案的說明,並使用單詞「正是如此」的=) – Tyrsius
@Tyrsius:我有[成功](http://connect.microsoft.com/VisualStudio/feedback/details/658392/linq-to-entities-order by-is-lost-when-after-first-first-default)在[Visual Studio和.NET]下記錄錯誤(https://connect.microsoft.com/VisualStudio/反饋) – StriplingWarrior