我有2個簡單的表格。Lambda查詢翻譯.count作爲選擇行(EF6代碼優先)
郵政是主人,有n票。我想用他們的投票計數返回帖子。 這是我的代碼:
db.posts.Select(p=>
new PostlDto{Title= p.Title, VoteCount= p.Votes.Count})
這是確定的,我有1個來電,獲得職位,並多次打電話給得到計數。 但問題是,它每次選擇行而不是對它們進行計數這是一個耗時的操作。 這是SQL事件探查器顯示我
exec sp_executesql N'SELECT
[Extent1].[Id] AS [Id],
[Extent1].[PostId] AS [PostId],
FROM [dbo].[Votes] AS [Extent1]
WHERE [Extent1].[PostId] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=6
我也試圖通過在基本查詢票表走數1通話,但它也需要太長的時間,因爲它也返回行,而不是它們的數量。 :|
db.posts
.Include(p=>p.Votes)
.Select(p=>
new PostlDto{Title= p.Title, VoteCount= p.Votes.Count})
這是將它轉換爲
SELECT
[Project1].[Id] AS [Id],
[Project1].[Title] AS [Title],
[Project1].[C1] AS [C1],
[Project1].[Id1] AS [Id1],
[Project1].[Pid] AS [Pid],
[Project1].[PostId] AS [PostId],
FROM (SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Title] AS [Title],
[Extent2].[Id] AS [Id1],
[Extent2].[PostId] AS [PostId],
CASE WHEN ([Extent2].[Id] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
FROM [dbo].[Posts] AS [Extent1]
LEFT OUTER JOIN [dbo].[Votes] AS [Extent2] ON [Extent1].[Id] = [Extent2].[PostId]
) AS [Project1]
ORDER BY [Project1].[Id] ASC, [Project1].[C1] ASC
我怎樣才能改變它來運行一個簡單的計數,而不是查詢? :|
這些查詢需要幾秒鐘才能運行!
請回答不增加的問題。 –
@CodyGray,好吧然後把它放在哪裏? David已回答David –
您已在David的回答下評論過。您可能會建議進行編輯以使實際解決方案更加清晰。爲了使該編輯得到批准,您需要編寫非常清晰的編輯摘要。 –