Integrating GraphQL with Entity Framework and Supabase
Written on
Chapter 1: Introduction to GraphQL and Supabase
In a previous article, I explored Hot Chocolate without incorporating a database, giving a foundational understanding of setting up a GraphQL server. However, that left out data persistence. In this guide, I will demonstrate how to configure PostgreSQL through Supabase and utilize it within your GraphQL queries. For a smoother experience, consider reviewing my earlier article to familiarize yourself with the foundational code.
Section 1.1: Adding Required EF Packages
To get started, we need to include some essential packages for PostgreSQL and data seeding. Use the following commands to add these packages:
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL
dotnet add package Microsoft.EntityFrameworkCore.Design
Next, we will add the Hot Chocolate Entity Framework package, which, while not strictly necessary, simplifies our code and improves integration:
dotnet add package HotChocolate.Data.EntityFramework
Subsection 1.1.1: Defining the Data Model
To represent our data, we need to create an entity. In the newly created Models folder, create a file named Todos.cs. This file will contain one primary key and two required fields: Label and Status.
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace graphql_medium.Models;
[Table("Todo")]
public class Todo
{
[Key]
[Required]
public int Id { get; set; }
[Required]
public string Label { get; set; }
[Required]
public string Status { get; set; }
}
Section 1.2: Setting Up the Database Context
To interact with our data, we need to establish a database context that outlines how we will retrieve todos. Moreover, we will seed the database with two todos, each having a distinct status.
using Microsoft.EntityFrameworkCore;
namespace graphql_medium.Models;
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions options) : base(options) { }
public DbSet<Todo> Todos => Set<Todo>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Todo>().HasData(
new { Id = 1, Label = "Walk a dog", Status = "DONE" },
new { Id = 2, Label = "Shopping", Status = "DOING" }
);
}
}
Section 1.3: Configuring the Connection String
To connect to PostgreSQL, I will add my Supabase credentials to the appsettings.json. Alternatively, you can opt for a local PostgreSQL instance or any preferred service.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"DefaultConnection": "Server=aws-0-eu-central-1.pooler.supabase.com;Port=5432;Database=postgres;Username=postgres.blwgtexcqaoodiqofuep;Password=ukgnPQZUUoZPNQh1"},
"AllowedHosts": "*"
}
Chapter 2: Registering and Migrating the DbContext
To ensure that our application can utilize the database, we must specify the connection string location and register the PostgreSQL connector. This will also allow the Hot Chocolate Resolver Compiler to manage the injection of the scoped DbContext instance into resolvers, preventing parallel execution.
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection"))
);
builder.Services
.AddGraphQLServer()
.RegisterDbContext()
.AddQueryType();
Applying migrations is essential to propagate our data into the database. We will execute the following commands to prepare and apply the migration:
dotnet ef migrations add Initial
dotnet ef database update Initial
Chapter 3: Executing Queries
Now that our data is set up, we can create queries to access it. Below is an example of how to utilize DbContext to retrieve our data effectively.
using graphql_medium.Models;
namespace graphql_medium.Service;
public class Query
{
public string GetGreeting() => "Hello World!";
public IQueryable<Todo> GetTodos(ApplicationDbContext db) => db.Todos;
public IQueryable<Todo> GetTodosDone(ApplicationDbContext db) => db.Todos.Where(t => t.Status == "DONE");
}
Section 3.1: Running the Application
To run your application, execute the following command:
dotnet run --launch-profile "https"
- Query 1: Todos
- Query 2: Completed Todos
Congratulations! You have successfully linked PostgreSQL with your GraphQL queries, showcasing different data outputs for the two queries.
If you found this guide insightful, consider joining our community by following us for more knowledge-sharing opportunities. Your feedback is appreciated!
Stackademic
Thank you for your attention! Don’t forget to clap and follow the writer! 👏 Follow us on X | LinkedIn | YouTube | Discord. Check out our other platforms: In Plain English | CoFeed | Venture.
This video titled "GraphQL with EF Core 6 and HotChocolate 12 - YouTube" provides a comprehensive overview of integrating GraphQL with Entity Framework Core and HotChocolate.
Watch "A Guide to Entity Framework with Hot Chocolate 13 - YouTube" for detailed insights on using Entity Framework with Hot Chocolate.