Hot Chocolate is the premier GraphQL server for .NET. Unlike Rest APIs, GraphQL allows clients to ask for exactly what they need, solving over-fetching. Hot Chocolate 11 brings massive performance improvements and the “Banana Cake Pop” IDE.
Schema Definition (Code-First)
public class Query
{
public IQueryable<Book> GetBooks([Service] ApplicationDbContext db) =>
db.Books;
}
// Startup.cs
services
.AddGraphQLServer()
.AddQueryType<Query>()
.AddProjections() // IQueryable to SQL translation!
.AddFiltering()
.AddSorting();
Handling Relationships (DataLoaders)
The “N+1 Problem” is the enemy of GraphQL. Use DataLoaders to batch requests.
public class Book
{
public int AuthorId { get; set; }
// Resolver
public async Task<Author> GetAuthorAsync(
[Service] AuthorDataLoader loader,
CancellationToken ct)
{
return await loader.LoadAsync(AuthorId, ct);
}
}
Key Takeaways
- Use **Projections** to let Hot Chocolate generate efficient SQL via EF Core.
- Use **DataLoaders** to prevent N+1 queries.
- Banana Cake Pop is a great tool for testing queries.
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.