当选择包含整个元素而不是其中的一部分时,EF将产生多个查询(n + 1),而不是带有子查询的单个查询。
按照https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/new-db?tabs=visual-studio
设置项目 context.Blogs.Select(a => new { a.Url, a.Posts.Count }).ToList();
运行此
SELECT [a].[Url], (
SELECT COUNT(*)
FROM [Posts] AS [p]
WHERE [a].[BlogId] = [p].[BlogId]
) AS [Count]
FROM [Blogs] AS [a]
但是
context.Blogs.Select(a => new { a, a.Posts.Count }).ToList();
运行此
SELECT [a].[BlogId], [a].[Url]
FROM [Blogs] AS [a];
exec sp_executesql N'SELECT COUNT(*)
FROM [Posts] AS [p0]
WHERE @_outer_BlogId = [p0].[BlogId]',N'@_outer_BlogId int',@_outer_BlogId=2
如何在不生成多个查询的情况下重新构造linq以选择整个Blog对象?据我所见,使用include并没有帮助。