GraphQL in ASP.NET Core
GraphQL in ASP.NET Core Mastery Guide
👤 Rohan Kumawat⏱️ 12 min read
🧠 What is GraphQL?
GraphQL is a query language for APIs and a runtime for executing queries by using a type system you define for your data.
It was developed by Facebook to solve issues commonly faced with REST APIs, such as over-fetching, under-fetching, and multiple round trips between client and server.
In GraphQL, the client defines exactly what data it needs — nothing more, nothing less.
GraphQl Setup in 5 Minutes:
Install the Package:
dotnet add package HotChocolate.AspNetCore
Create SQL Table:
CREATE TABLE [dbo].[Books](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Title] [nvarchar](max) NOT NULL,
[Author] [nvarchar](max) NOT NULL,
[Genre] [nvarchar](max) NOT NULL,
CONSTRAINT [PK_Books] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
Step-1: Create New WebApiProject
Step-2: Create Book.cs Models Folder. BookDto.cs and BookDto1.cs in Dto Folder
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public string Genre { get; set; }
}
public class BookDto
{
public string Title { get; set; }
public string Author { get; set; }
public string Genre { get; set; }
}
public class BookDto1
{
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public string Genre { get; set; }
}
Step-3: Create ApplicationDbContext.cs in Models Folder.
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions options) : base(options)
{
}
public DbSet Books { get; set; }
}
Step-4: Register ApplicationDbContext.cs in Program.cs
builder.Services.AddDbContext(x =>
x.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
Step-5: Add Services BookService.cs class and IBookService.cs interface
public interface IBooksService
{
IEnumerable GetBooks();
Book? GetBookById(int id);
Book? GetBookByName(string name);
string InsertBook(BookDto book);
string UpdateBook(BookDto1 book);
string DeleteBook(int id);
}
public class BooksService : IBooksService
{
private readonly Models.ApplicationDbContext _context;
public BooksService(Models.ApplicationDbContext context)
{
_context = context;
}
public IEnumerable GetBooks()
{
return _context.Books.ToList();
}
public Models.Book? GetBookById(int id)
{
return _context.Books.Find(id);
}
public Models.Book? GetBookByName(string name)
{
return _context.Books.FirstOrDefault(b => b.Title == name);
}
public string InsertBook(BookDto book)
{
var newBook = new Models.Book
{
Title = book.Title,
Author = book.Author,
Genre = book.Genre
};
_context.Books.Add(newBook);
_context.SaveChanges();
return "Book inserted successfully.";
}
public string UpdateBook(BookDto1 book)
{
var existingBook = _context.Books.Find(book.Id);
existingBook.Author = book.Author;
existingBook.Title = book.Title;
existingBook.Genre = book.Genre;
if (existingBook == null)
{
return "Book not found.";
}
_context.Books.Update(existingBook);
_context.SaveChanges();
return "Book updated successfully.";
}
public string DeleteBook(int id)
{
var book = _context.Books.Find(id);
if (book == null)
{
return "Book not found.";
}
_context.Books.Remove(book);
_context.SaveChanges();
return "Book deleted successfully.";
}
}
Step-6: Register BookService.cs and IBookService.cs in Program.cs
builder.Services.AddScoped();
Step-7: Create Query.cs and Mutation.cs classes
public class Query
{
private readonly IBooksService booksService;
public Query(IBooksService booksService)
{
this.booksService = booksService;
}
public IEnumerable GetBooks() => booksService.GetBooks();
public Book? GetBookById(int id) => booksService.GetBookById(id);
public Book? GetBookByName(string name) => booksService.GetBookByName(name);
}
public class Mutation
{
private readonly IBooksService booksService;
public Mutation(IBooksService booksService)
{
this.booksService = booksService;
}
public string InsertBook(BookDto book) => booksService.InsertBook(book);
public string UpdateBook(BookDto1 book) => booksService.UpdateBook(book);
public string DeleteBook(int id) => booksService.DeleteBook(id);
}
Step-7: Register the Query.cs and Mutation.cs classes in Program.cs
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services
.AddGraphQLServer()
.AddQueryType()
.AddMutationType();
Step-8: Finalize Things
builder.Services.AddAuthorization();
app.UseAuthorization();
app.MapGraphQL();
Never forget to add Authorization, because HotChocolate Package comes with inbuilt authorization, so you would have to add Authorization middle ware, other wise it'll cause you issue while to run the application.
Want Code Explation? Watch our playlist : https://www.youtube.com/playlist?list=PLXHXaMtGeiEMvl12QQvweJLL7Q8drvMjn
Subscribe to our youtube channel for exclusive content.