【发布时间】:2019-01-06 18:41:36
【问题描述】:
我有非常简单的模型
.NET Core 2.1 / EF Core 2.1 / MSSQL
public class ImageZ
{
[Key]
public Guid Id { get; set; }
public string Base64 { get; set; }
public string Title { get; set; }
}
public class Gallery
{
[Key]
public Guid Id { get; set; }
public ImageZ MainImage { get; set; }
public List<ImageZ> Images { get; set; } = new List<ImageZ>();
}
我正在使用这个 LINQ 从 db 加载它
return _context
.Gallery
.Include(x => x.Images)
.Include(x => x.MainImage)
.OrderBy(x => Guid.NewGuid())
.FirstOrDefault();
但它会向 db 发送两个查询
SELECT TOP(1) [x].[Id], [x].[MainImageId], [x.MainImage].[Id], [x.MainImage].[Base64], [x.MainImage].[GalleryId], [x.MainImage].[Title]
FROM [Gallery] AS [x]
LEFT JOIN [ImageZ] AS [x.MainImage] ON [x].[MainImageId] = [x.MainImage].[Id]
ORDER BY NEWID(), [x].[Id]
SELECT [x.Images].[Id], [x.Images].[Base64], [x.Images].[GalleryId], [x.Images].[Title]
FROM [ImageZ] AS [x.Images]
INNER JOIN (
SELECT DISTINCT [t].*
FROM (
SELECT TOP(1) [x0].[Id], NEWID() AS [c]
FROM [Gallery] AS [x0]
LEFT JOIN [ImageZ] AS [x.MainImage0] ON [x0].[MainImageId] = [x.MainImage0].[Id]
ORDER BY [c], [x0].[Id]
) AS [t]
) AS [t0] ON [x.Images].[GalleryId] = [t0].[Id]
ORDER BY [t0].[c], [t0].[Id]
这是正确的行为吗?不应该只用一个吗?
【问题讨论】:
-
不,实际上这是一个很大的改进。在 EF6 中,很容易包含多个 blow up the SQL result set both in length and in width。执行多个相对较小的查询可以防止这种情况。性能的关键是查询是在一批中执行的。
-
@GertArnold 那么,我不应该尝试从这个 LINQ 中获得更好的东西吗?
-
不,让 EF 自己动手。如果你操纵它,当 EF 以后让它变得更好时,你就完蛋了。
标签: c# sql linq-to-sql .net-core entity-framework-core