November 16, 2021 by Anuraj Estimated read time : 5 mins
This post is about GraphQL in ASP.NET Core with EF Core. In the earlier post I discussed about integrating GraphQL in ASP.NET Core with HotChocolate. In this post I will discuss about how to use GraphQL on top EF Core.
First I will be adding nuget packages required to work with EF Core - Microsoft.EntityFrameworkCore.SqlServer and Microsoft.EntityFrameworkCore.Design - this optional, since I am running migrations this package is required. Next I am modifying the code - adding DbContext and wiring the the DbContext to the application. Here is the DbContext code and updated Query class.
I wrote the OnModelCreating method to seed the database. And I modified the code of the Program.cs and added the DbCotext class.
And Query class modified like this.
In this code the Service attribute will help to inject the DbContext to the method. Next lets run the application and execute query.
We will be able to see result like this.
Next let us remove some parameters in the query and run it again.
We can see the result like this.
And when we look into the EF Core log, we will be able to see the EF Core SQL Log like this.
In the Log, even though we are querying only two fields it is querying all the fields. We can fix this issue by adding a new nuget package HotChocolate.Data.EntityFramework. And modify the code like this.
And modify the query class as well, decorate with the HotChocolate attributes for Projections, Filtering and Sorting.
Now lets run the query again and check the logs.
We can see only the required fields are queried. Not every fields in the table.
This way you can configure GraphQL in ASP.NET Core with EF Core. This code will fail, if you try to execute the GraphQL query with alias. We can use the DbContextFactory class to fix this issue. We will look into it in the next blog post.