我在實體框架中的linq查詢有問題。我正在查詢導航屬性上的某個字段。問題是生成的sql不夠理想。下面的例子被簡化了,實際上我試圖傳遞一個表達式樹,這就是爲什麼使用let綁定的第二個查詢不是一個足夠的解決方案,即使生成的sql是我想要的。這些查詢爲什麼會生成不同的sql?
所以總結我有兩個問題:
爲什麼生成的sql不同?有沒有什麼辦法來產生一個SQL查詢不會創建每個標準與表達式樹的聯接?
更新:我意識到,我必須包含(「證券」)的第一個查詢,而不是第二次,當我第一次張貼的問題,但它不會改變審覈規定的應用方式,僅列選擇。
var qry = db.Positions
.Where(criteria)
.ToList();
var qry1 = (from p in db.Positions
where p.Security.Country == "NO" || p.Security.Country == "US" || p.Security.Country == "GB"
select p).ToList();
var qry2 = (from p in db.Positions
let s = p.Security
where s.Country == "NO" || s.Country == "US" || s.Country == "GB"
select p).ToList();
--qry1
SELECT
[Extent1].* --All columns from tblPositions
FROM [dbo].[tblPositions] AS [Extent1]
LEFT OUTER JOIN [dbo].[tblSecurities] AS [Extent2] ON ([Extent2].[SecurityType] IN (1,2..)) AND ([Extent1].[Security] = [Extent2].[SecuritySeq])
LEFT OUTER JOIN [dbo].[tblSecurities] AS [Extent3] ON ([Extent3].[SecurityType] IN (1,2..)) AND ([Extent1].[Security] = [Extent3].[SecuritySeq])
LEFT OUTER JOIN [dbo].[tblSecurities] AS [Extent4] ON ([Extent4].[SecurityType] IN (1,2..)) AND ([Extent1].[Security] = [Extent4].[SecuritySeq])
LEFT OUTER JOIN [dbo].[tblSecurities] AS [Extent5] ON ([Extent5].[SecurityType] IN (1,2..)) AND ([Extent1].[Security] = [Extent5].[SecuritySeq])
WHERE [Extent2].[Country] = 'NO' OR [Extent3].[Country] = 'US' OR [Extent4].[Country] = 'GB'
--qry2
SELECT
[Extent1].*
FROM [dbo].[tblPositions] AS [Extent1]
LEFT OUTER JOIN [dbo].[tblSecurities] AS [Extent2] ON ([Extent2].[SecurityType] IN (1,2..)) AND ([Extent1].[Security] = [Extent2].[SecuritySeq])
WHERE [Extent2].[Country] IN ('NO','US','GB')
哪個版本EF這是? –
@GertArnold 6.0.2 –