如何查看实体框架生成的SQL?
(在我的特殊情况下,我正在使用mysql提供程序 - 如果它很重要)
我正在 Microsoft Entity Framework Core 3.0 中运行一个相当简单的查询,如下所示:
var dbProfile = db.Profiles.Where(x => x.SiteId == Int32.Parse(id))
    .Include(x => x.Interests)
    .Include(x => x.Pets)
    .Include(x => x.Networks)
    .Include(x => x.PersonalityTraits)
    .SingleOrDefault();
它在 EF Core 2.2.6 上运行良好,但是当升级到 EF Core 3.0 时,此查询会立即针对 721 个配置文件运行,但对于至少一个配置文件,查询超时:
Microsoft.Data.SqlClient.SqlException: '执行超时已过期。
操作完成之前超时时间已过或服务器没有响应。
然后我记录了发送到数据库服务器的实际查询:
SELECT [t].[Id], [t].[Age], [t].[City], [t].[Country], [t].[County], [t].[DeactivatedAccount], [t].[Gender], [t].[HasPictures], [t].[LastLogin], [t].[MemberSince], [t].[PresentationUpdated], [t].[ProfileName], [t].[ProfilePictureUrl], [t].[ProfileText], [t].[SiteId], [t].[VisitorsCount], [i].[Id], [i].[Name], [i].[ProfileId], [p0].[Id], [p0].[Description], [p0].[Name], [p0].[ProfileId], [n].[Id], [n].[Name], [n].[NetworkId], [n].[ProfileId], [p1].[Id], [p1].[Name], [p1].[ProfileId]
FROM (
    SELECT TOP(2) [p].[Id], …c# sql-server entity-framework entity-framework-core entity-framework-core-3.0
我有一个父实体,具有子实体的导航属性。只要子实体中存在关联记录,父实体就不能被删除。子实体可以包含数十万条记录。
我想知道在实体框架中最有效的做法是什么:
var parentRecord = _context.Where(x => x.Id == request.Id)
                           .Include(x => x.ChildTable)
                           .FirstOrDefault();
// check if parentRecord exists
if (parentRecord.ChildTable.Any()) {
  // cannot remove
}
或者
var parentRecord = _context.Where(x => x.Id == request.Id)
                            .Select(x => new {
                                  ParentRecord = x,
                                  HasChildRecords = x.ChildTable.Any()
                            })
                           .FirstOrDefault();
// check if parentRecord exists
if (parentRecord.HasChildRecords) {
  // cannot remove
}
第一个查询可能包含数千条记录,而第二个查询则不会,但是第二个查询更复杂。
哪种方法最好?