Hot Chocolatev15
This is documentation for v15, which is currently in preview.
See the latest stable version instead.

Fetching from Databases

In this section, you find a simple example on how you can fetch data from a database and expose it as a GraphQL API.

Hot Chocolate is not bound to a specific database, pattern or architecture. We do have a few integrations, that help with a variety of databases, though these are just additions on top of HotChocolate. You can couple your business logic close to the GraphQL server, or cleanly decouple your domain layer from the GraphQL layer over abstractions. The GraphQL server only knows its schema, types and resolvers, what you do in these resolvers and what types you expose, is up to you.

In this example, we will directly fetch data from MongoDB in a resolver.

Setting up the Query

The query type in a GraphQL schema is the root type. Each field defined on this type is available at the root of a query. If a field is requested, the resolver of the field is called. The data of this resolver is used for further execution. If you return a scalar, value (e.g. string, int ...) the value is serialized and added to the response. If you return an object, this object is the parent of the resolver in the subtree.

C#
// Query.cs
public class Query
{
public Task<Book?> GetBookById(IMongoCollection<Book> collection, Guid id)
{
return collection.Find(x => x.Id == id).FirstOrDefaultAsync();
}
}
// Book.cs
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
}
// Program.cs
builder.Services
.AddGraphQLServer()
.AddQueryType<Query>();