AjL*_*ing 5 performance database-performance psql entity-framework-core
我有这个查询,为了简洁起见,我将简化它:
public IQueryable<User> GetByIdAsync(Guid userId)
{
return MyContext
.Users
//Bunch of Includes
//Most of which have a ThenInclude
//Followed by another ThenInclude
.FirstOrDefaultAsync(u => u.Id == userId)
}
Run Code Online (Sandbox Code Playgroud)
当为大约 100 个用户运行时,需要超过 15 秒(在我的计算机上本地运行)。不是很好。
我尝试过使用AsNoTracking(),以及将其更改为使用已编译的查询,如下所示:
private static Func<MyContext, Guid, Task<User>> _getByIdAsync =
EF.CompileAsyncQuery((MyContext context, Guid userId) =>
context
.Users
//Same Includes as above
.Where(u => u.Id == userId)
.FirstOrDefault());
public IQueryable<User> GetByIdAsync(Guid userId)
{
return await _getByIdAsync(userId);
}
Run Code Online (Sandbox Code Playgroud)
还是没有区别。
我查看了相关线程的答案,它建议使用普通的旧 SQL:
我查看了这个答案,其中提到了聚集索引:
我当然不能排除其中任何一个,Includes因为客户依赖于所有这些信息。在这个阶段,重新设计也不是一个选择。
问题
你有很多方法,但这取决于情况。
.FirstOrDefaultAsync(u => u.Id == userId)对于 100 个用户,您将访问数据库 100 次,因此总计 15 000 / 100 == 等于每个请求 150 毫秒。in为了改进它,尝试使用类似的子句一次获取所有 100 个用户.Where(u=> userIds.contains(u.Id))例子。
private static Func<MyContext, Guid, Task<List<User>>> _getByIdAsync =
EF.CompileAsyncQuery((MyContext context, List<Guid> userIds) =>
context
.Users
//Same Includes as above
.Where(u => userIds.Contains(u.Id))).ToListAsync();
Run Code Online (Sandbox Code Playgroud)
如何使用联接进行查询的示例
var query = (from users in context.Users
join otherTable in context.OtherTable on users.Id equals otherTable.UserId).ToList();
Run Code Online (Sandbox Code Playgroud)
您可以使用此示例获取 sql
public IQueryable<User> GetByIdAsync(Guid userId)
{
var = query = MyContext
.Users
//Bunch of Includes
//Most of which have a ThenInclude
//Followed by another ThenInclude
var sql = query.ToSql(); // <--------------------------- sql query
return query.FirstOrDefaultAsync(u => u.Id == userId)
}
Run Code Online (Sandbox Code Playgroud)
并使用 sql 查询来分析并查看其是否使用索引。
最后,我真的很讨厌这样的方法public IQueryable GetByIdAsync(Guid userId)问题是大多数时候你不需要所有包含的内容,但是你开始越来越多地使用它们并变得依赖它们......这就是为什么我会推荐使用不带存储库模式的 EF,EF 本身是存储库,仅从数据库获取您需要的数据。
| 归档时间: |
|
| 查看次数: |
2113 次 |
| 最近记录: |