Building GraphQL API With .Net 5 - EF Core And Hot Chocolate

Introduction 

 
GraphQL is an open-source query language, originally developed by Facebook. It was in the year 2012 that Facebook chose to modify its applications to improve execution and productivity. It was the point at which Facebook's portable methodology wasn't working on account of high organization use. Enhancement techniques utilizing reserving may have improved the exhibition, yet since the application was excessively unpredictable, it was believed that the information bringing system itself ought to be changed. Here's the place where GraphQL came in, and today it has gotten amazingly mainstream among the advancement local area around the world. GraphQL, created by Facebook in 2012 and publicly released in 2015, is presently kept up by the GraphQL Foundation. This article examines the highlights and advantages of GraphQL and afterward shows how one can function with GraphQL in .Net 5.0.
 
Topics to be covered
  • Prerequisites
  • Why do we need GraphQL
  • What is HotChocolate
  • In-depth understanding of GraphQL Queries
  • Configuring GraphQL Middleware in .Net 5 
Prerequisites
  1. Visual Studio 2019 - Download here
  2. .Net 5.0 SDK - Download here
Download Source Code - GitHub
 

Why do we need GraphQL?

  • GraphQL is a JSON-like query language for APIs as well as a server-side runtime for executing your queries. Unlike REST where the request and response are defined by the API, in GraphQL, the client has complete control over what data the API should return. You can integrate GraphQL with ASP.NET, ASP.NET Core, Java, Python,Node.js, etc.
  • In the event that you are dealing with an application that uses RESTful design, the endpoints may develop over the long haul, and keeping up with them may turn into a bad dream. Despite what might be expected, with GraphQL, you simply need one endpoint programming api/graphql, and there's nothing more to it. This is another critical distinction between REST and GraphQL.
  • In utilizing GraphQL you need fewer roundtrips to the worker, i.e., you need fewer to and fro calls to the worker to get all the information you need. With REST, you will have a few endpoints like programming api/understudies, api/educators, api/groups, and so on
  • In contrast to REST, when utilizing GraphQL, you won't ever have nearly nothing or a lot of information – you can characterize your questions and all information you need.
  • When utilizing GraphQL, you need not stress over forming. The truth of the matter is that GraphQL doesn't require forming and as long as you don't erase fields from the sorts, the customers or shoppers of the API wouldn't break.
  • Like Swagger creates documentation for the REST endpoints, GraphQL can likewise produce documentation for the GraphQL endpoint.

What is HotChocolate?

 
HotChocolate is a .Net GraphQL Platform that can help you build a GraphQL layer over your existing and new application.HotChoclate is very easy to setup and takes the clutter away from writing the GraphQL Schemas. 
 

 In-depth understanding of GraphQL

 
Schema
 
A GraphQL schema is a description of the data clients can request from a GraphQL API. It also defines the queries and mutation functions that the client can use to read and write data from the GraphQL server. In other words, you specify your client or application UI data requirements in your GraphQL schema.
 
The schema contains a Query and Mutation
 
Query fetch data - like a GET in the rest
 
Mutation changes data - like DELETE or a POST  in rest.
 
Some people use the word query to refer to both GraphQL queries and mutations.
 

Configuring the GraphQL Middleware  

 
Setup the Project - Choose the Empty Asp.Net core project.
 
Building GraphQL API With .Net 5 - EF Core And Hot Chocolate 
 
Building GraphQL API With .Net 5 - EF Core And Hot Chocolate 
 
Packages used to configure the EF Core and GraphQL
 
Building GraphQL API With .Net 5 - EF Core And Hot Chocolate 
 
Create an empty folder Model and inside that will add the respective Model and Data context.
 
                             Building GraphQL API With .Net 5 - EF Core And Hot Chocolate
 
Create a Model class to perform the Database operation using Entity Framework Core using Code first approach
 
Employee.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace GraphQL_HotChoclate_EFCore.Models  
  8. {  
  9.     public class Employee  
  10.     {   
  11.         [Key]  
  12.         public int Id { get; set; }  
  13.         public string Name { get; set; }  
  14.         public string Designation { get; set; }  
  15.     }  
  16. }  
Define all the classes inside this DatabaseContext class and adding the static data by using the seed data mechanism.
 
DatabaseContext.cs
  1. using Microsoft.EntityFrameworkCore;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace GraphQL_HotChoclate_EFCore.Models  
  8. {  
  9.     public class DatabaseContext : DbContext  
  10.     {  
  11.         public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)  
  12.         {  
  13.   
  14.         }  
  15.         public DbSet<Employee> Employees { get; set; }  
  16.   
  17.         #region Seed Data  
  18.         protected override void OnModelCreating(ModelBuilder modelBuilder)  
  19.         {  
  20.             modelBuilder.Entity<Employee>().HasData(  
  21.                 new Employee  
  22.                 {  
  23.                     Id =1,  
  24.                     Name = "Jay krishna Reddy",  
  25.                     Designation = "Full Stack Developer"  
  26.                 },  
  27.                 new Employee  
  28.                 {  
  29.                     Id = 2,  
  30.                     Name = "JK",  
  31.                     Designation = "SSE"  
  32.                 },  
  33.                 new Employee   
  34.                 {  
  35.                     Id = 3,  
  36.                     Name = "Jay",  
  37.                     Designation = "Software Engineer"  
  38.                 },  
  39.                 new Employee  
  40.                 {  
  41.                     Id = 4,  
  42.                     Name = "krishna Reddy",  
  43.                     Designation = "Database Developer"  
  44.                 },  
  45.                 new Employee  
  46.                 {  
  47.                     Id = 5,  
  48.                     Name = "Reddy",  
  49.                     Designation = "Cloud Engineer"  
  50.                 }  
  51.                 );  
  52.         }  
  53.         #endregion  
  54.   
  55.     }  
  56. }  
 Add the connection string in the appsettings.json file
 
appsettings.json 
  1. {  
  2.   "Logging": {  
  3.     "LogLevel": {  
  4.       "Default""Information",  
  5.       "Microsoft""Warning",  
  6.       "Microsoft.Hosting.Lifetime""Information"  
  7.     }  
  8.   },  
  9.   "AllowedHosts""*",  
  10.   "ConnectionStrings": {  
  11.     "myconn""server="Your server name"; database=GraphQL;Trusted_Connection=True;"  
  12.   }  
  13. }  
 add the SQL server configuration setup in a Startup.cs file under the Configure services method.
 
Startup.cs 
  1. using GraphQL_HotChoclate_EFCore.GraphQL;  
  2. using GraphQL_HotChoclate_EFCore.Models;  
  3. using GraphQL_HotChoclate_EFCore.Services;  
  4. using HotChocolate;  
  5. using HotChocolate.AspNetCore;  
  6. using HotChocolate.AspNetCore.Playground;  
  7. using Microsoft.AspNetCore.Builder;  
  8. using Microsoft.AspNetCore.Hosting;  
  9. using Microsoft.AspNetCore.Http;  
  10. using Microsoft.EntityFrameworkCore;  
  11. using Microsoft.Extensions.Configuration;  
  12. using Microsoft.Extensions.DependencyInjection;  
  13. using Microsoft.Extensions.Hosting;  
  14. using System;  
  15. using System.Collections.Generic;  
  16. using System.Linq;  
  17. using System.Threading.Tasks;  
  18.   
  19. namespace GraphQL_HotChoclate_EFCore  
  20. {  
  21.     public class Startup  
  22.     {  
  23.         public IConfiguration Configuration { get; }  
  24.         // This method gets called by the runtime. Use this method to add services to the container.  
  25.         // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940  
  26.         public Startup(IConfiguration configuration)  
  27.         {  
  28.             Configuration = configuration;  
  29.         }  
  30.          
  31.         public void ConfigureServices(IServiceCollection services)  
  32.         {  
  33.             #region Connection String  
  34.             services.AddDbContext<DatabaseContext>(item => item.UseSqlServer(Configuration.GetConnectionString("myconn")));  
  35.             #endregion  
  36.       
  37.         }  
  38.   
  39.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  40.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  41.         {  
  42.             if (env.IsDevelopment())  
  43.             {  
  44.                 app.UseDeveloperExceptionPage();  
  45.              
  46.             }   
  47.             app.UseRouting();  
  48.   
  49.             app.UseEndpoints(endpoints =>  
  50.             {  
  51.                 endpoints.MapGet("/", async context =>  
  52.                 {  
  53.                     await context.Response.WriteAsync("Hello World!");  
  54.                 });  
  55.             });  
  56.         }  
  57.     }  
  58. }  
Create the database and tables in the SQL server by using the below commands.
  1. Add-Migration 'Migration Name'   -- To create the Script inside the solution project
  2. update-database  --  To execute the generated script in the sql server
Execute the Table in SQL Server to check the data 
 
                Building GraphQL API With .Net 5 - EF Core And Hot Chocolate 
 
Now, will add the services to have all our business logic in them.
 
Building GraphQL API With .Net 5 - EF Core And Hot Chocolate
EmployeeService.cs 
  1. using GraphQL_HotChoclate_EFCore.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.EntityFrameworkCore;  
  7.   
  8. namespace GraphQL_HotChoclate_EFCore.Services  
  9. {  
  10.     public class EmployeeService : IEmployeeService  
  11.     {  
  12.         #region Property  
  13.         private readonly DatabaseContext _dbContext;  
  14.         #endregion  
  15.   
  16.         #region Constructor  
  17.         public EmployeeService(DatabaseContext databaseContext)  
  18.         {  
  19.             _dbContext = databaseContext;  
  20.         }  
  21.         #endregion  
  22.   
  23.         public async Task<Employee> Create(Employee employee)  
  24.         {  
  25.             var data = new Employee  
  26.             {  
  27.                 Name = employee.Name,  
  28.                 Designation = employee.Designation  
  29.             };  
  30.             await _dbContext.Employees.AddAsync(data);  
  31.             await _dbContext.SaveChangesAsync();  
  32.             return data;  
  33.         }  
  34.         public async Task<bool> Delete(DeleteVM deleteVM)  
  35.         {  
  36.             var employee = await  _dbContext.Employees.FirstOrDefaultAsync(c => c.Id == deleteVM.Id);  
  37.             if(employee is not null)   
  38.             {  
  39.                 _dbContext.Employees.Remove(employee);  
  40.                 await _dbContext.SaveChangesAsync();  
  41.                 return true;  
  42.             }  
  43.             return false;  
  44.         }  
  45.         public IQueryable<Employee> GetAll()  
  46.         {  
  47.             return _dbContext.Employees.AsQueryable();  
  48.         }  
  49.     }  
  50.   
  51.     public class DeleteVM  
  52.     {  
  53.         public int Id { get; set; }  
  54.     }  
  55. }  
 IEmployeeService.cs
  1. using GraphQL_HotChoclate_EFCore.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace GraphQL_HotChoclate_EFCore.Services  
  8. {  
  9.    public interface IEmployeeService  
  10.     {  
  11.         Task<Employee> Create(Employee employee);  
  12.         Task<bool> Delete(DeleteVM deleteVM);  
  13.         IQueryable<Employee> GetAll();  
  14.     }  
  15. }  
 add this  Employeeservice dependency in the startup. cs under the ConfigureServices Method.
  1. services.AddScoped<IEmployeeService,EmployeeService>();  
After completion of the table creation, Now let's integrate the GraphQL in step by step process.
 
create an empty folder named GraphQL where will add the Query class and Mutation class to perform the GraphQL operations with respect to its GraphQLTypes.
 
Building GraphQL API With .Net 5 - EF Core And Hot Chocolate
 
Define the Employee services in the Query and Mutation class
 
Query.cs
  1. using GraphQL_HotChoclate_EFCore.Models;  
  2. using GraphQL_HotChoclate_EFCore.Services;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace GraphQL_HotChoclate_EFCore.GraphQL  
  9. {  
  10.     public class Query  
  11.     {  
  12.         #region Property  
  13.         private readonly IEmployeeService _employeeService;  
  14.         #endregion  
  15.   
  16.         #region Constructor  
  17.         public Query(IEmployeeService employeeService)  
  18.         {  
  19.             _employeeService = employeeService;  
  20.         }  
  21.         #endregion  
  22.   
  23.         public IQueryable<Employee> Employees => _employeeService.GetAll();  
  24.          
  25.     }  
  26. }  
Mutation.cs
  1. using GraphQL_HotChoclate_EFCore.Models;  
  2. using GraphQL_HotChoclate_EFCore.Services;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace GraphQL_HotChoclate_EFCore.GraphQL  
  9. {  
  10.     public class Mutuation  
  11.     {  
  12.         #region Property  
  13.         private readonly IEmployeeService _employeeService;  
  14.         #endregion  
  15.   
  16.         #region Constructor  
  17.         public Mutuation(IEmployeeService employeeService)  
  18.         {  
  19.             _employeeService = employeeService;  
  20.         }  
  21.         #endregion  
  22.         public async Task<Employee> Create(Employee employee) => await _employeeService.Create(employee);  
  23.         public async Task<bool> Delete(DeleteVM deleteVM) => await _employeeService.Delete(deleteVM);  
  24.     }  
  25. }  
GraphQLTypes.cs
 
Invoke the Employee class inside the objectype by using the Hotchocolate library. 
  1. using GraphQL_HotChoclate_EFCore.Models;  
  2. using HotChocolate.Types;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace GraphQL_HotChoclate_EFCore.GraphQL  
  9. {  
  10.     public class GraphQLTypes :ObjectType<Employee>  
  11.     {  
  12.   
  13.     }  
  14. }  
Configure the GraphQL Middleware in the Startup.cs file by adding the GraphQL Model class and hot chocolate playground is the tool that will help to query the data (GraphQL).
 
Startup.cs   --- final version 
  1. using GraphQL_HotChoclate_EFCore.GraphQL;  
  2. using GraphQL_HotChoclate_EFCore.Models;  
  3. using GraphQL_HotChoclate_EFCore.Services;  
  4. using HotChocolate;  
  5. using HotChocolate.AspNetCore;  
  6. using HotChocolate.AspNetCore.Playground;  
  7. using Microsoft.AspNetCore.Builder;  
  8. using Microsoft.AspNetCore.Hosting;  
  9. using Microsoft.AspNetCore.Http;  
  10. using Microsoft.EntityFrameworkCore;  
  11. using Microsoft.Extensions.Configuration;  
  12. using Microsoft.Extensions.DependencyInjection;  
  13. using Microsoft.Extensions.Hosting;  
  14. using System;  
  15. using System.Collections.Generic;  
  16. using System.Linq;  
  17. using System.Threading.Tasks;  
  18.   
  19. namespace GraphQL_HotChoclate_EFCore  
  20. {  
  21.     public class Startup  
  22.     {  
  23.         public IConfiguration Configuration { get; }  
  24.         // This method gets called by the runtime. Use this method to add services to the container.  
  25.         // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940  
  26.         public Startup(IConfiguration configuration)  
  27.         {  
  28.             Configuration = configuration;  
  29.         }  
  30.          
  31.         public void ConfigureServices(IServiceCollection services)  
  32.         {  
  33.             #region Connection String  
  34.             services.AddDbContext<DatabaseContext>(item => item.UseSqlServer(Configuration.GetConnectionString("myconn")));  
  35.             #endregion  
  36.             services.AddScoped<Query>();  
  37.             services.AddScoped<Mutuation>();  
  38.             services.AddScoped<IEmployeeService,EmployeeService>();  
  39.             services.AddGraphQL(c => SchemaBuilder.New().AddServices(c).AddType<GraphQLTypes>()  
  40.                                                                         .AddQueryType<Query>()  
  41.                                                                         .AddMutationType<Mutuation>()  
  42.                                                                          .Create());  
  43.         }  
  44.   
  45.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  46.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  47.         {  
  48.             if (env.IsDevelopment())  
  49.             {  
  50.                 app.UseDeveloperExceptionPage();  
  51.                 app.UsePlayground(new PlaygroundOptions  
  52.                 {  
  53.                     QueryPath = "/api",  
  54.                     Path = "/playground"  
  55.                 });  
  56.             }  
  57.             app.UseGraphQL("/api");  
  58.             app.UseRouting();  
  59.   
  60.             app.UseEndpoints(endpoints =>  
  61.             {  
  62.                 endpoints.MapGet("/", async context =>  
  63.                 {  
  64.                     await context.Response.WriteAsync("Hello World!");  
  65.                 });  
  66.             });  
  67.         }  
  68.     }  
  69. }  
Run the project  
 
Add the playground tag to the URL  - https://localhost:44330/playground/  this playground will actually take us to the hot-chocolate tool in which we can do our querying (GraphQL).
 
Overview of the HotChocolate Platform
 
Building GraphQL API With .Net 5 - EF Core And Hot Chocolate
 
Fetch all the list of employees by using the query
 
Building GraphQL API With .Net 5 - EF Core And Hot Chocolate 
 
Create the user by using the mutation 
 
Building GraphQL API With .Net 5 - EF Core And Hot Chocolate
 
Delete the user 
 
Building GraphQL API With .Net 5 - EF Core And Hot Chocolate

Conclusion

 
In this article, we have covered all the topics related to GraphQl and its usage and the integration with .Net 5.0, EF Core with performing the CRUD Operations. Hope this gives you a clear idea in understanding and as well as in implementation.
 
Many thanks for reading...! 
 
Happy Coding... !


Similar Articles