GraphQL With Hot Chocolate Using ASP.NET Core

Introduction

 
We will try to do a CRUD operation using graphQL with Hot Chocolate using Asp.net Core.
 
First of all we will understand what GraphQL and Hot Chocolate are.
 

GraphQL

 
GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.
 
GraphQL follows the same set of constraints as REST APIs, but it organizes data into a graph using one interface. Objects are represented by nodes (defined using the GraphQL schema), and the relationship between nodes is represented by edges in the graph. Each object is then backed by a resolver that accesses the server’s data.
 

Hot Chocolate

 
Hot Chocolate is a .NET GraphQL platform that can help you build a GraphQL layer over your existing and new infrastructure.
 
Our API will let you start very quickly with pre-built templates that let you start in seconds.
 
Pre Requirements
  • Sql server 2019
  • Visual studio
Now we start.
 
Firstly come to SQL server and create tables.
  1. SET ANSI_NULLS ON  
  2. GO  
  3. SET QUOTED_IDENTIFIER ON  
  4. GO  
  5. CREATE TABLE [dbo].[Department](  
  6. [DepartmentId] [int] IDENTITY(1,1) NOT NULL,  
  7. [Name] [varchar](50) NULL,  
  8. CONSTRAINT [PK_Department] PRIMARY KEY CLUSTERED  
  9. (  
  10.    [DepartmentId] ASC  
  11. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  12. ON [PRIMARY]  
  13. GO  
  14. SET ANSI_NULLS ON  
  15. GO  
  16. SET QUOTED_IDENTIFIER ON  
  17. GO  
  18. CREATE TABLE [dbo].[Employee](  
  19. [EmployeeId] [int] IDENTITY(1,1) NOT NULL,  
  20. [Name] [varchar](50) NULL,  
  21. [Email] [varchar](50) NULL,  
  22. [Age] [intNULL,  
  23. [DepartmentId] [intNULL,  
  24. CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED  
  25. (  
  26.    [EmployeeId] ASC  
  27. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  28. ON [PRIMARY]  
  29. GO  
Now come to Visual Studio and create a new web application.
 
After that you add some nuget package
 
GraphQL with Hot Chocolate using Asp.net Core
 
GraphQL with Hot Chocolate using Asp.net Core
 
GraphQL with Hot Chocolate using Asp.net Core
 
GraphQL with Hot Chocolate using Asp.net Core
 
GraphQL with Hot Chocolate using Asp.net Core
 
GraphQL with Hot Chocolate using Asp.net Core
 
Below are the list of nuget packages:
  1. Install-Package Microsoft.EntityFrameworkCore -Version 5.0.3  
  2. Install-Package Microsoft.EntityFrameworkCore.SqlServer  
  3. Install-Package HotChocolate -Version 11.0.9  
  4. Install-Package HotChocolate.AspNetCore -Version 11.0.9  
  5. Install-Package GraphQL  
  6. Install-Package graphiql -Version 2.0.0  
Now in your project you haveto  add folder model.
 
Under the model create a class department.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.ComponentModel.DataAnnotations.Schema;  
  5. using System.Linq;  
  6. using System.Threading.Tasks;  
  7. namespace Asp.netCoreGraphQL.Model {  
  8.     public class Department {  
  9.         [Key]  
  10.         [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
  11.         public int DepartmentId {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public string Name {  
  16.             get;  
  17.             set;  
  18.         }  
  19.         public ICollection < Employee > Employees {  
  20.             get;  
  21.             set;  
  22.         }  
  23.     }  
  24. }  
In the above class you see  <Employee> error not found ,
 
So now we create a new class under the model folder employee.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.ComponentModel.DataAnnotations.Schema;  
  5. using System.Linq;  
  6. using System.Threading.Tasks;  
  7. namespace Asp.netCoreGraphQL.Model {  
  8.     public class Employee {  
  9.         [Key]  
  10.         [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
  11.         public int EmployeeId {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         [Required]  
  16.         public string Name {  
  17.             get;  
  18.             set;  
  19.         }  
  20.         [Required]  
  21.         [EmailAddress]  
  22.         public string Email {  
  23.             get;  
  24.             set;  
  25.         }  
  26.         [Required]  
  27.         [Range(minimum: 20, maximum: 50)]  
  28.         public int Age {  
  29.             get;  
  30.             set;  
  31.         }  
  32.         public int DepartmentId {  
  33.             get;  
  34.             set;  
  35.         }  
  36.         public Department Department {  
  37.             get;  
  38.             set;  
  39.         }  
  40.     }  
  41. }  
Now create a DbContext class under the Model Folder SampleAppDbContext
  1. using Microsoft.EntityFrameworkCore;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6. namespace Asp.netCoreGraphQL.Model {  
  7.     public class SampleAppDbContext: DbContext {  
  8.         public SampleAppDbContext(DbContextOptions < SampleAppDbContext > options): base(options) {}  
  9.         public DbSet < Employee > Employee {  
  10.             get;  
  11.             set;  
  12.         }  
  13.         public DbSet < Department > Department {  
  14.             get;  
  15.             set;  
  16.         }  
  17.     }  
  18. }  
Now add connectionstrings in the appsettings.json file.
  1. {  
  2.     "ConnectionStrings": {  
  3.         "SampleAppDbContext""Data Source=AJAYKUMAR-VWIPL\\MSSQLSERVERS;Initial Catalog=Test;Integrated Security=True;"  
  4.     },  
  5.     "Logging": {  
  6.         "LogLevel": {  
  7.             "Default""Information",  
  8.             "Microsoft""Warning",  
  9.             "Microsoft.Hosting.Lifetime""Information"  
  10.         }  
  11.     },  
  12.     "AllowedHosts""*"  
  13. }  
Now create a new folder repository.
 
Under the repository folder we have a class DepartmentRepository
  1. using Asp.netCoreGraphQL.Model;  
  2. using Microsoft.EntityFrameworkCore;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Threading.Tasks;  
  7. namespace Asp.netCoreGraphQL.Repository {  
  8.     public class DepartmentRepository {  
  9.         private readonly SampleAppDbContext _sampleAppDbContext;  
  10.         public DepartmentRepository(SampleAppDbContext sampleAppDbContext) {  
  11.             _sampleAppDbContext = sampleAppDbContext;  
  12.         }  
  13.         public List < Department > GetAllDepartmentOnly() {  
  14.             return _sampleAppDbContext.Department.ToList();  
  15.         }  
  16.         public List < Department > GetAllDepartmentsWithEmployee() {  
  17.             return _sampleAppDbContext.Department.Include(d => d.Employees).ToList();  
  18.         }  
  19.         public async Task < Department > CreateDepartment(Department department) {  
  20.             await _sampleAppDbContext.Department.AddAsync(department);  
  21.             await _sampleAppDbContext.SaveChangesAsync();  
  22.             return department;  
  23.         }  
  24.     }  
  25. }  
And now under repository folder create another class EmployeeRepository.
  1. using Asp.netCoreGraphQL.Model;  
  2. using Microsoft.EntityFrameworkCore;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Threading.Tasks;  
  7. namespace Asp.netCoreGraphQL.Repository {  
  8.     public class EmployeeRepository {  
  9.         private readonly SampleAppDbContext _sampleAppDbContext;  
  10.         public EmployeeRepository(SampleAppDbContext sampleAppDbContext) {  
  11.             _sampleAppDbContext = sampleAppDbContext;  
  12.         }  
  13.         public List < Employee > GetEmployees() {  
  14.             return _sampleAppDbContext.Employee.ToList();  
  15.         }  
  16.         public Employee GetEmployeeById(int id) {  
  17.             var employee = _sampleAppDbContext.Employee.Include(e => e.Department).Where(e => e.EmployeeId == id).FirstOrDefault();  
  18.             if (employee != nullreturn employee;  
  19.             return null;  
  20.         }  
  21.         public async Task < Employee > UPdateEmployeeByIdAsync(int id, string Name) {  
  22.             var employee = _sampleAppDbContext.Employee.Include(e => e.Department).Where(e => e.EmployeeId == id).FirstOrDefault();  
  23.             employee.Name = Name;  
  24.             await _sampleAppDbContext.SaveChangesAsync();  
  25.             if (employee != nullreturn employee;  
  26.             return null;  
  27.         }  
  28.         public List < Employee > GetEmployeesWithDepartment() {  
  29.             return _sampleAppDbContext.Employee.Include(e => e.Department).ToList();  
  30.         }  
  31.         public async Task < Employee > CreateEmployee(Employee employee) {  
  32.             await _sampleAppDbContext.Employee.AddAsync(employee);  
  33.             await _sampleAppDbContext.SaveChangesAsync();  
  34.             return employee;  
  35.         }  
  36.     }  
  37. }  
Now we have create new folder DataAccess.
 
Under the DataAcess folder to create a class Mutation.
  1. using Asp.netCoreGraphQL.Model;  
  2. using Asp.netCoreGraphQL.Repository;  
  3. using HotChocolate;  
  4. using HotChocolate.Subscriptions;  
  5. using System;  
  6. using System.Collections.Generic;  
  7. using System.Linq;  
  8. using System.Threading.Tasks;  
  9. namespace Asp.netCoreGraphQL.DataAccess {  
  10.     public class Mutation {  
  11.         public async Task < Department > CreateDepartment([Service] DepartmentRepository departmentRepository,  
  12.             [Service] ITopicEventSender eventSender, string departmentName) {  
  13.             var newDepartment = new Department {  
  14.                 Name = departmentName  
  15.             };  
  16.             var createdDepartment = await departmentRepository.CreateDepartment(newDepartment);  
  17.             await eventSender.SendAsync("DepartmentCreated", createdDepartment);  
  18.             return createdDepartment;  
  19.         }  
  20.         public async Task < Employee > CreateEmployeeWithDepartmentId([Service] EmployeeRepository employeeRepository, string name, int age, string email, int departmentId) {  
  21.             Employee newEmployee = new Employee {  
  22.                 Name = name,  
  23.                     Age = age,  
  24.                     Email = email,  
  25.                     DepartmentId = departmentId  
  26.             };  
  27.             var createdEmployee = await employeeRepository.CreateEmployee(newEmployee);  
  28.             return createdEmployee;  
  29.         }  
  30.         public async Task < Employee > CreateEmployeeWithDepartment([Service] EmployeeRepository employeeRepository, string name, int age, string email, string departmentName) {  
  31.             Employee newEmployee = new Employee {  
  32.                 Name = name,  
  33.                     Age = age,  
  34.                     Email = email,  
  35.                     Department = new Department {  
  36.                         Name = departmentName  
  37.                     }  
  38.             };  
  39.             var createdEmployee = await employeeRepository.CreateEmployee(newEmployee);  
  40.             return createdEmployee;  
  41.         }  
  42.     }  
  43. }  
Now create anothe class under the DataAccess folder query.
  1. using Asp.netCoreGraphQL.Model;  
  2. using Asp.netCoreGraphQL.Repository;  
  3. using HotChocolate;  
  4. using HotChocolate.Subscriptions;  
  5. using System;  
  6. using System.Collections.Generic;  
  7. using System.Linq;  
  8. using System.Threading.Tasks;  
  9. namespace Asp.netCoreGraphQL.DataAccess {  
  10.     public class Query {  
  11.         public List < Employee > AllEmployeeOnly([Service] EmployeeRepository employeeRepository) => employeeRepository.GetEmployees();  
  12.         public List < Employee > AllEmployeeWithDepartment([Service] EmployeeRepository employeeRepository) => employeeRepository.GetEmployeesWithDepartment();  
  13.         public async Task < Employee > GetEmployeeById([Service] EmployeeRepository employeeRepository,  
  14.             [Service] ITopicEventSender eventSender, int id) {  
  15.             Employee gottenEmployee = employeeRepository.GetEmployeeById(id);  
  16.             await eventSender.SendAsync("ReturnedEmployee", gottenEmployee);  
  17.             return gottenEmployee;  
  18.         }  
  19.         public async Task < Employee > UpdateEmployeeById([Service] EmployeeRepository employeeRepository,  
  20.             [Service] ITopicEventSender eventSender, int id, string name) {  
  21.             Employee gottenEmployee = await employeeRepository.UPdateEmployeeByIdAsync(id, name);  
  22.             await eventSender.SendAsync("ReturnedEmployee", gottenEmployee);  
  23.             return gottenEmployee;  
  24.         }  
  25.         public List < Department > AllDepartmentsOnly([Service] DepartmentRepository departmentRepository) => departmentRepository.GetAllDepartmentOnly();  
  26.         public List < Department > AllDepartmentsWithEmployee([Service] DepartmentRepository departmentRepository) => departmentRepository.GetAllDepartmentsWithEmployee();  
  27.     }  
  28. }  
Now create another class under the DataAccess folder subscription
  1. using Asp.netCoreGraphQL.Model;  
  2. using HotChocolate;  
  3. using HotChocolate.Execution;  
  4. using HotChocolate.Subscriptions;  
  5. using HotChocolate.Types;  
  6. using System;  
  7. using System.Collections.Generic;  
  8. using System.Linq;  
  9. using System.Threading;  
  10. using System.Threading.Tasks;  
  11. namespace Asp.netCoreGraphQL.DataAccess {  
  12.     public class Subscription {  
  13.         [SubscribeAndResolve]  
  14.         public async ValueTask < ISourceStream < Department >> OnDepartmentCreate([Service] ITopicEventReceiver eventReceiver, CancellationToken cancellationToken) {  
  15.                 return await eventReceiver.SubscribeAsync < string, Department > ("DepartmentCreated", cancellationToken);  
  16.             }  
  17.             [SubscribeAndResolve]  
  18.         public async ValueTask < ISourceStream < Employee >> OnEmployeeGet([Service] ITopicEventReceiver eventReceiver, CancellationToken cancellationToken) {  
  19.             return await eventReceiver.SubscribeAsync < string, Employee > ("ReturnedEmployee", cancellationToken);  
  20.         }  
  21.     }  
  22. }  
Now change under the Startup.cs
  1. using Asp.netCoreGraphQL.DataAccess;  
  2. using Asp.netCoreGraphQL.Model;  
  3. using Asp.netCoreGraphQL.Repository;  
  4. using Microsoft.AspNetCore.Builder;  
  5. using Microsoft.AspNetCore.Hosting;  
  6. using Microsoft.EntityFrameworkCore;  
  7. using Microsoft.Extensions.Configuration;  
  8. using Microsoft.Extensions.DependencyInjection;  
  9. using Microsoft.Extensions.Hosting;  
  10. using System;  
  11. using System.Collections.Generic;  
  12. using System.Linq;  
  13. using System.Threading.Tasks;  
  14. namespace Asp.netCoreGraphQL {  
  15.     public class Startup {  
  16.         private readonly string AllowedOrigin = "allowedOrigin";  
  17.         public Startup(IConfiguration configuration) {  
  18.             Configuration = configuration;  
  19.         }  
  20.         public IConfiguration Configuration {  
  21.             get;  
  22.         }  
  23.         // This method gets called by the runtime. Use this method to add services to the container.  
  24.         public void ConfigureServices(IServiceCollection services) {  
  25.             // services.AddRazorPages();  
  26.             services.AddDbContext < SampleAppDbContext > (options => options.UseSqlServer(Configuration.GetConnectionString("SampleAppDbContext")));  
  27.             services.AddInMemorySubscriptions();  
  28.             services.AddGraphQLServer().AddQueryType < Query > ().AddMutationType < Mutation > ().AddSubscriptionType < Subscription > ();  
  29.             services.AddScoped < EmployeeRepository, EmployeeRepository > ();  
  30.             services.AddScoped < DepartmentRepository, DepartmentRepository > ();  
  31.             services.AddCors(option => {  
  32.                 option.AddPolicy("allowedOrigin", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());  
  33.             });  
  34.         }  
  35.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  36.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {  
  37.             if (env.IsDevelopment()) {  
  38.                 app.UseDeveloperExceptionPage();  
  39.             }  
  40.             app.UseCors(AllowedOrigin);  
  41.             app.UseWebSockets();  
  42.             app.UseRouting().UseEndpoints(endpoints => {  
  43.                 endpoints.MapGraphQL();  
  44.             });  
  45.         }  
  46.     }  
  47. }  
Now the coding part is done and we can execute the code. 
 
After The url you add /graphql/
 
Your URL looks like: 
 
http://localhost:61280/graphql/
 
GraphQL with Hot Chocolate using Asp.net Core
 
This is called Banana Cake popup.
 
Now we start our CRUD operation.
 
Create Query
  1. mutation {  
  2.     createEmployeeWithDepartment(name: "Ajay", age: 30, email: "[email protected]", departmentName: "IT") {  
  3.         departmentId  
  4.         name  
  5.         department {  
  6.             departmentId  
  7.             name  
  8.         }  
  9.     }  
  10. }  
GraphQL with Hot Chocolate using Asp.net Core
 
In BananaCake popup you see execute button. In the left hand side there are inputs and in the right hand side there are responses.
 
Show The OutPut
  1. query {  
  2.     allDepartmentsWithEmployee {  
  3.         name  
  4.         employees {  
  5.             email  
  6.             name  
  7.         }  
  8.     }  
  9. }  
The response:
  1. {  
  2.     "data": {  
  3.         "allDepartmentsWithEmployee": [{  
  4.             "name""IT",  
  5.             "employees": [{  
  6.                 "email""[email protected]",  
  7.                 "name""Ajay"  
  8.             }]  
  9.         }]  
  10.     }  
  11. }  
Show the output using some filter
  1. query {  
  2.     employeeById(id: 16) {  
  3.         name  
  4.         email  
  5.     }  
  6. }  
Response:
  1. {  
  2.     "data": {  
  3.         "employeeById": {  
  4.             "name""Ajay",  
  5.             "email""[email protected]"  
  6.         }  
  7.     }  
  8. }  
Update the code:
  1. query {  
  2.     updateEmployeeById(id: 16, name: "Ajay Kumar") {  
  3.         name,  
  4.         email,  
  5.         department {  
  6.             name  
  7.         }  
  8.     }  
  9. }  
Response
  1. {  
  2.     "data": {  
  3.         "updateEmployeeById": {  
  4.             "name""Ajay Kumar",  
  5.             "email""[email protected]",  
  6.             "department": {  
  7.                 "name""IT"  
  8.             }  
  9.         }  
  10.     }  
  11. }  
NOTE
You can run your graphQL query using the postman

GraphQL with Hot Chocolate using Asp.net Core
 

Summary

 
I have done CRUD operation using GraphQL with Hot Chocolate using asp.net core. I hope you understand. If you have any query and suggestion then please leave a comment.