Using data loaders
In the previous section, we learned how to integrate HotChocolate with EF Core. We also learned how to use the DbContextPool
feature to fetch data in multiple resolvers. However, we found that there are many database queries for each Department
object in the Teacher
list. That is because the resolvers for each Department
object are executed separately, querying the database by each DepartmentId
property in the list. This is similar to the N+1 problem we discussed in Chapter 1. The difference is that the N+1 problem occurs on the client side in REST APIs, while it occurs on the server side in GraphQL. To solve this problem, we need to find a way to load the batch data efficiently.
HotChocolate provides a DataLoader
mechanism to solve the N+1 problem. The data loader fetches data in batches from the data source. Then, the resolver can retrieve the data from the data loader, rather than querying the data source directly. The data loader will cache the data for the...