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.

query {
  a:links {
    title
    url
    description
    imageUrl
  }
  b:links {
    title
    url
    description
    imageUrl
  }
  c:links {
    title
    url
    description
    imageUrl
  }
}

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.

Graph QL endpoint - Entity Framework Core - Error

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.

using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContextFactory<BookmarkDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("BookmarkDbConnection")));
builder.Services.AddGraphQLServer().AddQueryType<Query>().AddProjections().AddFiltering().AddSorting();
var app = builder.Build();

app.MapGet("/", () => "Hello World!");
app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapGraphQL();
});
app.Run();

And we need to modify the query class as well.

public class Query
{
    [UseDbContext(typeof(BookmarkDbContext))]
    [UseProjection]
    [UseFiltering]
    [UseSorting]
    public IQueryable<Link> Links([ScopedService] BookmarkDbContext bookmarkDbContext)
            => bookmarkDbContext.Links;
}

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