GraphQL in .NET Core - Part 1

Expose an entity using HotChocolate

This article assumes that you know the basics of working with Entity Framework and that you have a sample application that has an entity that you want to expose through GraphQL.

Let's assume that you have the following model that you use to create an entity in your database:

using System.ComponentModel.DataAnnotations;  

namespace Example.Models;  

public class Country
    public int Id { get; set; }  
    public string Name { get; set; }  

How can we go about creating a GraphQL endpoint that exposes this model?

The answer to this is quite simple and in this article, I want to show you how to do it using the HotChocolate framework.

Here are the steps:

  1. Install the following NuGet packages (we are assuming you already have the required nuget packages for Entity framework installed)

     dotnet add package HotChocolate.AspNetCore
     dotnet add package HotChocolate.Data.Entityframework
  2. Create a Query.cs file in your project (it can be within a folder if you want) and add the following code to it:

     // DbContext is in Data - referencing it here
     using Example.Data;  
     using Example.Models;  
     namespace Example.GraphQL;  
     public class Query  
         // Service - this is a special attribute that allows us to inject a service into our resolver method
         public IQueryable<Platform> GetCountries([Service] AppDbContext context) => context.Country;  
  3. Update the Program.cs file to add the GraphQL middleware and endpoint:

     using Example.Data;  
     using Example.GraphQL;  
     using Microsoft.EntityFrameworkCore;  
     var builder = WebApplication.CreateBuilder(args);  
     // Add our database reference to handler
     builder.Services.AddDbContext<AppDbContext>(opt => opt.UseSqlServer("name=ConStr"));
     // GraphQL related config - note that we pass our Query class type  
     var app = builder.Build();  
     // This will allow us to reach our graphQL endpoing
     app.UseEndpoints(endpoints => { endpoints.MapGraphQL(); });  

We are going to assume that you have a connection string to your database in the appsettings.Development.json file already and you were able to update your database and can see the tables on the database server already.

That's all! - run the application and point to the /graphql path using your favorite API testing tool. I am using postman for this example:

A few things to note:

  1. All calls to GraphQL endpoints are done using the POST verb.

  2. We haven't taken advantage of relationships

  3. Concurrency has not been addressed

In the next post, we add cities into some of these countries and see how we can make GraphQL return us countries with cities inside them.