DEV Community

Spyros Ponaris
Spyros Ponaris

Posted on

Getting Started with GraphQL in ASP.NET

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
Enter fullscreen mode Exit fullscreen mode

Install the required packages:

dotnet add package HotChocolate.AspNetCore
dotnet add package HotChocolate.Data.EntityFramework
dotnet add package Microsoft.EntityFrameworkCore.InMemory
Enter fullscreen mode Exit fullscreen mode

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; }
}
Enter fullscreen mode Exit fullscreen mode

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>();
}
Enter fullscreen mode Exit fullscreen mode

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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"));
Enter fullscreen mode Exit fullscreen mode
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();
Enter fullscreen mode Exit fullscreen mode

Run Your First Query

Navigate to:

https://localhost:5001/graphql
Enter fullscreen mode Exit fullscreen mode

Execute:

query {
  products {
    id
    name
    price
  }
}
Enter fullscreen mode Exit fullscreen mode

Response:

{
  "data": {
    "products": [
      {
        "id": 1,
        "name": "Laptop",
        "price": 999.99
      },
      {
        "id": 2,
        "name": "Mouse",
        "price": 29.99
      }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

Register the features:

builder.Services
    .AddGraphQLServer()
    .AddQueryType<Query>()
    .AddFiltering()
    .AddSorting();
Enter fullscreen mode Exit fullscreen mode

Now clients can run queries like:

query {
  products(
    where: { price: { gt: 100 } }
    order: { price: DESC }
  ) {
    name
    price
  }
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)