我有以下代碼應該得到一些book
,並檢索該書(Book
實體)的前兩個tag
(Tag
實體)。 因此Tags
是Book
實體的navigation property
。實體框架6:Skip()&Take()不生成SQL,而是在加載到內存後過濾結果集。或者我做錯了什麼?
using (var context = new FakeEndavaBookLibraryEntities())
{
Book firstBook = context.Set<Book>().Take(1).First();
var firstTwoTags = firstBook.Tags.OrderBy(tag => tag.Id).Skip(0).Take(2).ToList();
}
我預計獲得有由EF生成以下SQL查詢。
SELECT TOP(2)
[Extent2].[Id] AS [Id],
[Extent2].[Version] AS [Version],
[Extent2].[Name] AS [Name]
FROM [Literature].[BookTagRelation] AS [Extent1]
INNER JOIN [Literature].[Tag] AS [Extent2]
ON [Extent1].[TagId] = [Extent2].[Id]
WHERE [Extent1].[BookId] = 1 /* @EntityKeyValue1 - [BookId] */
取而代之的是,EF探查表明我的EF是產生無限的結果集(如SELECT * FROM ...)
SELECT [Extent2].[Id] AS [Id],
[Extent2].[Version] AS [Version],
[Extent2].[Name] AS [Name]
FROM [Literature].[BookTagRelation] AS [Extent1]
INNER JOIN [Literature].[Tag] AS [Extent2]
ON [Extent1].[TagId] = [Extent2].[Id]
WHERE [Extent1].[BookId] = 1 /* @EntityKeyValue1 - [BookId] */
Here is a scheme fragment if you need it
我也試圖追加.AsQueryable()
至firstBook.Tags
財產和/或刪除.Skip(0)
方法,如下所示,但這也沒有幫助。
var firstTwoTags = firstBook.Tags.AsQueryable().OrderBy(tag => tag.Id).Skip(0).Take(2).ToList();
同樣意外的行爲:
SELECT [Extent2].[Id] AS [Id],
[Extent2].[Version] AS [Version],
[Extent2].[Name] AS [Name]
FROM [Literature].[BookTagRelation] AS [Extent1]
INNER JOIN [Literature].[Tag] AS [Extent2]
ON [Extent1].[TagId] = [Extent2].[Id]
WHERE [Extent1].[BookId] = 1 /* @EntityKeyValue1 - [BookId] */
你曾經與實體框架6工作時遇到同樣的問題?
是否有任何解決方法來克服這個問題,或者我設計了一個錯誤的方式查詢......?
感謝您的任何提示!
爲什麼使用Skip,Take和SingleOrDefault ?.如果你不關心標籤的數量,只需替換Skip()。Take()。SingleOrDefault()with .FirstOrDefault() –
@SebastianBrand老實說,我打算做分頁... by Skip(toBeSkipped )。取(pageSize的)'。我會更新問題以使其更清楚。 –