GraphQL in .NET

• By OmerZ Solutions

Modern applications require efficient and flexible APIs that can serve data exactly as requested by clients. Traditional REST APIs often lead to over-fetching or multiple unnecessary requests.

GraphQL solves this problem by allowing clients to request only the required data through a single endpoint. In this article, we will build a complete GraphQL API in .NET using a real-world example of Students and Courses.

GraphQL in .NET
GraphQL allows flexible querying, reduces API calls, and improves performance in modern backend systems.

What is GraphQL?

GraphQL is a query language for APIs that enables clients to request exactly the data they need. It was developed by Facebook and has become a popular alternative to REST APIs.

In .NET, GraphQL is commonly implemented using the HotChocolate library, which provides a powerful and flexible server implementation.

Core Features of This Implementation

  • Query Students
  • Add Student (Mutation)
  • Query Courses
  • Add Course (Mutation)

GraphQL Queries and Mutations

Query Students

query {
 students {
 id,
 name,
 email
 }
}

This query retrieves all students in a single request without multiple API calls.

Mutation - Add Student

mutation{
 addStudent(name:"Javed Ali", email: "javed@ali.com")
 {
 id,name,email
 }
}

This mutation inserts a new student into the database and returns the created record.

Query Courses

query {
 courses{
 id,
 courseName
 }
}

This query fetches all available courses efficiently.

Mutation - Add Course

mutation
{
 addCourse(courseName: "English")
 {
 id,courseName
 }
}

This mutation creates a new course entry and returns the inserted data.

Program.cs Configuration

The GraphQL server is configured in Program.cs using HotChocolate. It registers query and mutation types and connects them to application services.

using GraphQLDemoWithDotNet.Data;
using GraphQLDemoWithDotNet.GraphQL.Course;
using GraphQLDemoWithDotNet.GraphQL.Student;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<SchoolDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("StudentConn")));

builder.Services.AddGraphQLServer()
    .AddQueryType(d => d.Name("Query"))
    .AddTypeExtension<StudentQueries>()
    .AddTypeExtension<CourseQueries>()
    .AddMutationType(d => d.Name("Mutation"))
    .AddTypeExtension<StudentMutations>()
    .AddTypeExtension<CourseMutations>();

var app = builder.Build();

app.MapGraphQL();

app.Run();

Entity Models

These simple models represent database tables for Students and Courses.

public class Student
{
 public int ID { get; set; }
 public string Name { get; set; }
 public string Email { get; set; }
}

public class Course
{
 public int ID { get; set; }
 public string CourseName { get; set; }
}

DbContext Configuration

Entity Framework Core is used as ORM to manage database operations with SQL Server.

using Microsoft.EntityFrameworkCore;

public class SchoolDbContext : DbContext
{
 public DbSet<Student> Student { get; set; }
 public DbSet<Course> Course { get; set; }

 public SchoolDbContext(DbContextOptions options) : base(options) { }
}

GraphQL Queries

Queries define how data is fetched from the system.

[ExtendObjectType("Query")]
public class StudentQueries
{
 public List<Student> GetStudents([Service] SchoolDbContext schoolContext)
 {
 return schoolContext.Student.ToList();
 }

 public Student? GetStudentById(int ID, [Service] SchoolDbContext schoolContext)
 {
 return schoolContext.Student.FirstOrDefault(x => x.ID == ID);
 }
}
[ExtendObjectType("Query")]
public class CourseQueries
{
 public List<Course> GetCourses([Service] SchoolDbContext schoolContext)
 {
 return schoolContext.Course.ToList();
 }

 public Course? GetCourseById(int ID, [Service] SchoolDbContext schoolContext)
 {
 return schoolContext.Course.FirstOrDefault(c => c.ID == ID);
 }
}

GraphQL Mutations

Mutations are used to modify data such as creating or updating records.

[ExtendObjectType("Mutation")]
public class StudentMutations
{
 public Student AddStudent(string name, string email, [Service] SchoolDbContext schoolContext)
 {
 var student = new Student
 {
 Name = name,
 Email = email
 };

 schoolContext.Student.Add(student);
 schoolContext.SaveChanges();

 return student;
 }
}
[ExtendObjectType("Mutation")]
public class CourseMutations
{
 public Course AddCourse(string courseName, [Service] SchoolDbContext schoolContext)
 {
 var course = new Course
 {
 CourseName = courseName
 };

 schoolContext.Course.Add(course);
 schoolContext.SaveChanges();

 return course;
 }
}

Benefits of GraphQL in .NET

  • Reduces multiple API calls
  • Prevents over-fetching and under-fetching
  • Improves frontend performance
  • Single endpoint architecture
  • Strongly typed schema with HotChocolate

Conclusion

In this article, we built a complete GraphQL API in .NET using HotChocolate, Entity Framework Core, and SQL Server.

GraphQL provides a modern and efficient approach to API development, making backend systems more flexible and scalable compared to traditional REST APIs.

Need Help Building GraphQL APIs in .NET?

OmerZ Solutions helps businesses build scalable, high-performance backend systems using modern .NET technologies.

Contact Us