HotChocolate is an open-source .NET library for adding a GraphQL server to an ASP.NET Core application. It supplies GraphQL services and middleware, integrates with EF Core and authorization, and includes the browser-based BananaCakePop client for testing the endpoint. For a board-game API with an existing EF Core data model, these features avoid implementing the GraphQL runtime from scratch. section 10.2.3
To add it to an existing application:
- Install HotChocolate.AspNetCore, HotChocolate.AspNetCore.Authorization, and HotChocolate.Data.EntityFramework. The illustrated setup pins all three packages to version 12.15.2. section 10.2.3
- Define a Query class whose methods return IQueryable results from the EF Core database context. The board-game, domain, and mechanic queries use paging, projection, filtering, and sorting attributes. section 10.2.3
- Define mutations for changes to those entities. The illustrated update methods use DTO inputs and save through the database context; authorization attributes restrict them by role. section 10.2.3
- Register the query and mutation types with AddGraphQLServer(), enable the corresponding features, and map the endpoint with app.MapGraphQL(). section 10.2.3
Listing 10.6 Program.cs file: GraphQL services
using MyBGList.GraphQL; #1
// [...]
builder.Services.AddGraphQLServer() #2
.AddAuthorization() #3
.AddQueryType<Query>() #4
.AddMutationType<Mutation>() #5
.AddProjections() #6
.AddFiltering() #7
.AddSorting(); #8
The service-registration chain connects the query and mutation classes to authorization, projections, filtering, and sorting. section 10.2.3
Check the endpoint
Run the application and open BananaCakePop at the illustrated local /graphql endpoint. Request the first three board games, sorted by ID, with only id, name, and year; the response contains those fields. A second query requests their domains and mechanics in the same round trip. To check writes, run an authorized updateBoardGame mutation, then query that game again to confirm its new name. section 10.2.4
