GraphQL multiple requests and EF Core DbContext
November 16, 2021 by Anuraj
AspNetCore GraphQL DotNet6 EFCore
GraphQL support multiple operations in a single query. So that you can query multiple objects in a single request. Here is an example.
In this query we are looking for the same information in parallel - it can be any query operations for the demo purposes we are using the same. If you execute this code, you will be able to see the result like this.
It is showing a concurrency exception. It is because the DbContext is not thread safe. To fix this issue we can use the AddDbContextFactory
- it is a extension method introduced in .NET 5.0 - which helps to register a factory instead of registering the context type directly allows for easy creation of new DbContext instances. And in the code, we need to manage the DbContext object.
Let’s update the code to use AddDbContextFactory()
method.
And we need to modify the query class as well.
Now you can run the app again and you will be able to fetch the results without any issue.
You can find the source code in GitHub
Happy Programming :)
Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub