【发布时间】:2020-04-20 07:09:18
【问题描述】:
我目前正在使用这种方法通过AsNoTracking 加载实体及其相关实体:
await DbContext.Clients
.Include(x => x.AllowedGrantTypes)
.Include(x => x.RedirectUris)
.Include(x => x.PostLogoutRedirectUris)
.Include(x => x.AllowedScopes)
.Include(x => x.ClientSecrets)
.Include(x => x.Claims)
.Include(x => x.IdentityProviderRestrictions)
.Include(x => x.AllowedCorsOrigins)
.Include(x => x.Properties)
.Where(x => x.Id == clientId)
.AsNoTracking()
.SingleOrDefaultAsync();
Github 上的代码详情:link
这可行,但在迁移到 EF Core 3.0 后,此查询非常慢。
我发现可以通过像这样显式加载相关实体来解决这个性能问题:
IQueryable<Entities.Client> baseQuery = Context.Clients
.Where(x => x.Id == clientId)
.Take(1);
var client = await baseQuery.FirstOrDefaultAsync();
if (client == null) return null;
await baseQuery.Include(x => x.AllowedCorsOrigins).SelectMany(c => c.AllowedCorsOrigins).LoadAsync();
await baseQuery.Include(x => x.AllowedGrantTypes).SelectMany(c => c.AllowedGrantTypes).LoadAsync();
await baseQuery.Include(x => x.AllowedScopes).SelectMany(c => c.AllowedScopes).LoadAsync();
await baseQuery.Include(x => x.Claims).SelectMany(c => c.Claims).LoadAsync();
await baseQuery.Include(x => x.ClientSecrets).SelectMany(c => c.ClientSecrets).LoadAsync();
await baseQuery.Include(x => x.IdentityProviderRestrictions).SelectMany(c => c.IdentityProviderRestrictions).LoadAsync();
await baseQuery.Include(x => x.PostLogoutRedirectUris).SelectMany(c => c.PostLogoutRedirectUris).LoadAsync();
await baseQuery.Include(x => x.Properties).SelectMany(c => c.Properties).LoadAsync();
await baseQuery.Include(x => x.RedirectUris).SelectMany(c => c.RedirectUris).LoadAsync();
Github 上的代码详情:link
不幸的是,我尝试使用 AsNoTracking 方法重写此示例,但它不起作用 - 未加载相关实体。
如何使用 AsNoTracking 方法通过更快的性能重写我的原始查询?
我不需要为我的用例跟踪客户端实体。
【问题讨论】:
标签: asp.net-core .net-core ef-core-3.0