Getting Started with GraphQL in ASP.NET and EF Core
GraphQL is a modern API technology that allows clients to request exactly the data they need. Unlike traditional REST APIs, GraphQL uses a single endpoint and gives consumers more control over the response structure.
If you're building ASP.NET applications with Entity Framework Core, adding GraphQL can be a great way to expose your data efficiently.
Why GraphQL?
With REST APIs, clients often receive more data than they need or must call multiple endpoints to collect related information.
GraphQL helps solve these problems by providing:
- Flexible data retrieval
- Fewer API requests
- Strongly typed schemas
- Better performance for complex data scenarios
Create a New ASP.NET Project
Start by creating a Web API project:
dotnet new webapi -n GraphQLDemo
cd GraphQLDemo
Install the required packages:
dotnet add package HotChocolate.AspNetCore
dotnet add package HotChocolate.Data.EntityFramework
dotnet add package Microsoft.EntityFrameworkCore.InMemory
Create the Entity
Let's create a simple Product model:
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
}
Configure EF Core
Create a DbContext:
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Product> Products => Set<Product>();
}
Create a GraphQL Query
GraphQL queries define the data clients can request.
public class Query
{
public IQueryable<Product> GetProducts(
[Service] AppDbContext context)
{
return context.Products;
}
}
Returning IQueryable allows Hot Chocolate to optimize filtering, sorting, and projections.
Register Services
In Program.cs:
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseInMemoryDatabase("ProductsDb"));
builder.Services
.AddGraphQLServer()
.AddQueryType<Query>();
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
db.Products.AddRange(
new Product { Id = 1, Name = "Laptop", Price = 999.99m },
new Product { Id = 2, Name = "Mouse", Price = 29.99m }
);
db.SaveChanges();
}
app.MapGraphQL();
app.Run();
Run Your First Query
Navigate to:
https://localhost:5001/graphql
Execute:
query {
products {
id
name
price
}
}
Response:
{
"data": {
"products": [
{
"id": 1,
"name": "Laptop",
"price": 999.99
},
{
"id": 2,
"name": "Mouse",
"price": 29.99
}
]
}
}
Enable Filtering and Sorting
One of the best features of Hot Chocolate is built-in filtering and sorting.
Update the query:
using HotChocolate.Data;
public class Query
{
[UseFiltering]
[UseSorting]
public IQueryable<Product> GetProducts(
[Service] AppDbContext context)
{
return context.Products;
}
}
Register the features:
builder.Services
.AddGraphQLServer()
.AddQueryType<Query>()
.AddFiltering()
.AddSorting();
Now clients can run queries like:
query {
products(
where: { price: { gt: 100 } }
order: { price: DESC }
) {
name
price
}
}
Conclusion
GraphQL and EF Core work very well together in ASP.NET applications. With Hot Chocolate, you can expose database entities through GraphQL with minimal configuration while gaining powerful features like filtering, sorting, and projections.
If you're already using EF Core, adding GraphQL is an easy way to make your APIs more flexible and developer-friendly. Start with simple queries, then move on to mutations, authentication, and real database providers like SQL Server or PostgreSQL.
Happy coding! 🚀
References
- GraphQL Official Documentation, Learn GraphQL https://graphql.org/learn/
- GraphQL Official Documentation, Queries https://graphql.org/learn/queries/
- Hot Chocolate Documentation, Getting Started with GraphQL in .NET
https://chillicream.com/docs/hotchocolate/get-started-with-graphql-in-net-core
- Hot Chocolate Documentation, GraphQL Server for .NET https://chillicream.com/docs/hotchocolate
Top comments (0)