GraphQL In .NET Core Web API With Entity Framework Core - Part One

In this article, we will see how GraphQL works with Entity Framework Core and is exposed through Web API in .NET Core.

Let’s first understand why we use GraphQL when we directly expose data through a Web API endpoint. Consider a scenario where you want to create endpoints for the User Entity. So, you can expose the API like GetAllUsers, GetUsersByUserId, and GetUserByUserName in order to return limited fields like UserName and UserId, not the entire User entity. So again, you need to expose other endpoints and ultimately, we will end up with n number of endpoints which is very difficult to maintain. GraphQL helps us here as it’s a schema definition language. You need to expose only one endpoint which expects the GraphQL query and you can get your desired results with a single endpoint.

Let’s see step by step implementation of GraphQL in Web API.

Create an ASP.NET Core web application and select API as template and Core 2.0 as version

In our demo, we need GraphQL as well as Entity Framework Core, so add the NuGet Packages mentioned below.

  • GraphQL
  • GraphQL.Server.Transports.AspnetCore
  • GraphQL.Server.UI.Playground
  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.Tools
  • Microsoft.VisualStudio.Web.CodeGeneration.Design

Now, let’s create a database in MS SQL Server for our demo purposes. Also, create a table and add some dummy data. You can execute the below script in order to create a table with the data inside the GraphQLDemo database.

  1. USE [GraphQLDemo]  
  2. GO  
  3. /****** Object:  Table [dbo].[Employee]    Script Date: 2/2/2019 9:15:36 PM ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8. CREATE TABLE [dbo].[Employee](  
  9.     [Id] [bigint] IDENTITY(1,1) NOT NULL,  
  10.     [Name] [varchar](100) NULL,  
  11.     [Email] [varchar](50) NULL,  
  12.     [Mobile] [varchar](50) NULL,  
  13.     [Company] [varchar](100) NULL,  
  14.     [Address] [varchar](100) NULL,  
  15.     [ShortDescription] [varchar](1000) NULL,  
  16.     [LongDescription] [text] NULL,  
  17.  CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED   
  18. (  
  19.     [Id] ASC  
  20. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  21. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
  22. GO  
  23. SET IDENTITY_INSERT [dbo].[Employee] ON   
  24. GO  
  25. INSERT [dbo].[Employee] ([Id], [Name], [Email], [Mobile], [Company], [Address], [ShortDescription], [LongDescription]) VALUES (1, N'Akshay', N'akshayblevel@gmail.com', N'9999999999', N'Dotnetbees', N'Hyderabad', N'Short Description', N'Long Description')  
  26. GO  
  27. INSERT [dbo].[Employee] ([Id], [Name], [Email], [Mobile], [Company], [Address], [ShortDescription], [LongDescription]) VALUES (2, N'Panth', N'panth@gmail.com', N'8888888888', N'Radix', N'Vadodara', N'SD', N'LD')  
  28. GO  
  29. SET IDENTITY_INSERT [dbo].[Employee] OFF  
  30. GO  

In the next step, we need a connection string to connect with the database. So, as a normal practice, let’s store our connection string in Appsettings.json.

Appsettings.json

  1. "ConnectionStrings": {  
  2.     "DefaultConnection""Server=akshay-pc\\devsql2016;Database=GraphQLDemo;Trusted_Connection=True;MultipleActiveResultSets=true"  
  3.   }  

Run the scaffold command to generate the model and dbcontext class.

Open the Package Manager Console and execute the below command.

Scaffold-DbContext “Server=AKSHAY-PC\DEVSQL2016;Database=GraphQLDemo;Trusted_Connection=True;” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Employee.cs

  1. namespace GraphQLInWebApiCore  
  2. {  
  3.     public partial class Employee  
  4.     {  
  5.         public long Id { getset; }  
  6.         public string Name { getset; }  
  7.         public string Email { getset; }  
  8.         public string Mobile { getset; }  
  9.         public string Company { getset; }  
  10.         public string Address { getset; }  
  11.         public string ShortDescription { getset; }  
  12.         public string LongDescription { getset; }  
  13.     }  
  14. }  

GraphQLDemoContext

  1. using Microsoft.EntityFrameworkCore;  
  2.   
  3. namespace GraphQLInWebApiCore  
  4. {  
  5.     public partial class GraphQLDemoContext : DbContext  
  6.     {  
  7.         public GraphQLDemoContext()  
  8.         {  
  9.         }  
  10.   
  11.         public GraphQLDemoContext(DbContextOptions<GraphQLDemoContext> options)  
  12.             : base(options)  
  13.         {  
  14.         }  
  15.   
  16.         public virtual DbSet<Employee> Employee { getset; }  
  17.     }  
  18. }  

Add the DbContext under ConfigureServices in Startup.cs, which adds into the service collection and can be injected whenever required.

Startup.cs

  1. services.AddDbContext<GraphQLDemoContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  

Create an employee repository to get all the employees from the database through dbcontext, i.e., Entitiy Framework Core.

IEmployeeRepository.cs

  1. using System.Collections.Generic;  
  2. using System.Threading.Tasks;  
  3.   
  4. namespace GraphQLInWebApiCore  
  5. {  
  6.     public interface IEmployeeRepository  
  7.     {  
  8.         Task<List<Employee>> GetEmployees();  
  9.     }  
  10. }  

EmployeeRepository.cs

  1. using Microsoft.EntityFrameworkCore;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5.   
  6. namespace GraphQLInWebApiCore  
  7. {  
  8.     public class EmployeeRepository : IEmployeeRepository  
  9.     {  
  10.         private readonly GraphQLDemoContext _context;  
  11.         public EmployeeRepository(GraphQLDemoContext context)  
  12.         {  
  13.             _context = context;  
  14.         }  
  15.   
  16.         public Task<List<Employee>> GetEmployees()  
  17.         {  
  18.             return _context.Employee.ToListAsync();  
  19.         }  
  20.     }  
  21. }  

So far, we are done with -

  • Creating a table in DB
  • Adding sample data into the table
  • Configuring Entity Framework Core and setting the connection with a database
  • Creating a repository which will return the list of employees

Let’s start implementing GraphQL. This requires Schema, Query, and ObjectGraphType.

GraphQL In .NET Core Web API With Entity Framework Core 

We need to create EmployeeType which inherits ObjectGraphType<T> and set all the fields of an employee in the constructor.

  1. using GraphQL.Types;  
  2.   
  3. namespace GraphQLInWebApiCore  
  4. {  
  5.     public class EmployeeType : ObjectGraphType<Employee>  
  6.     {  
  7.         public EmployeeType()  
  8.         {  
  9.             Field(a => a.Id);  
  10.             Field(a => a.Name);  
  11.             Field(a => a.Email);  
  12.             Field(a => a.Mobile);  
  13.             Field(a => a.Company);  
  14.             Field(a => a.Address);  
  15.             Field(a => a.ShortDescription);  
  16.             Field(a => a.LongDescription);  
  17.         }  
  18.     }  
  19. }  

Create a query which will set the field of the previously created object graph type and internally fetch the data from the repository and resolve the context.

  1. using GraphQL.Types;  
  2.   
  3. namespace GraphQLInWebApiCore  
  4. {  
  5.     public class EmployeeQuery : ObjectGraphType  
  6.     {  
  7.         public EmployeeQuery(IEmployeeRepository employeeRepository)  
  8.         {  
  9.             Field<ListGraphType<EmployeeType>>(  
  10.                 "employees",  
  11.                 resolve: context => employeeRepository.GetEmployees()  
  12.                 );  
  13.         }  
  14.     }  
  15. }  

Schema will be used to resolve the query. We will resolve the previously created query; i.e., EmployeeQuery.

  1. using GraphQL;  
  2. using GraphQL.Types;  
  3.   
  4. namespace GraphQLInWebApiCore  
  5. {  
  6.     public class EmployeeSchema : Schema  
  7.     {  
  8.         public EmployeeSchema(IDependencyResolver resolver) : base(resolver)  
  9.         {  
  10.             Query = resolver.Resolve<EmployeeQuery>();  
  11.         }  
  12.     }  
  13. }  

Add the below code snippet under configureservices in startup.cs which will be used to resolve the dependency. That means we are adding interfaces and the concrete implementation against each interface inside the service collection.

  1. services.AddScoped<IEmployeeRepository, EmployeeRepository>();  
  2. //GraphQL configuration  
  3.        services.AddScoped<IDependencyResolver>(s => new FuncDependencyResolver(s.GetRequiredService));  
  4.        services.AddScoped<EmployeeSchema>();  
  5.        services.AddGraphQL(o => { o.ExposeExceptions = false; })  
  6.         .AddGraphTypes(ServiceLifetime.Scoped);  

Add the below code under configure method in startup.cs. With UseGraphQL method, we can set the path to access GraphQL in the parameter. But if you don’t set it, it will consider the /graphql path.

  1. app.UseGraphQL<EmployeeSchema>();  
  2. app.UseGraphQLPlayground(new GraphQLPlaygroundOptions());  

At the starting stage, we added a NuGet package called GraphQL.Server.UI.Playground which will provide the UI where we can write our GraphQL queries and at the same time, we can see the result. For that, we need to browse the ui/playground path. We can configure the same at the launch of the browser.

GraphQL In .NET Core Web API With Entity Framework Core 

Now, run the application and you can see that the UI is rendered in the browser where on the left side, we have a query input section and at the right side, the result section. In middle, we have an "Execute" button to execute the query. If you click on the Schema button which is in the extreme right side of the browser, you can see the query and graph object type. This detail will help to write the query.

GraphQL In .NET Core Web API With Entity Framework Core 

As soon as you start writing a query, IntelliSense will suggest query and object graph type that we have created.

GraphQL In .NET Core Web API With Entity Framework Core 
 
GraphQL In .NET Core Web API With Entity Framework Core 

Click the "Run" button and you can see the result; i.e., the list of employees on the right side. If you observe the query and result, we asked for the name and email fields of employees and we get the same as the result. This means we can pass a response parameter which we would like to return as a result and we will get that only.

GraphQL In .NET Core Web API With Entity Framework Core 

In the object graph type, we can add the description as well so that a user can understand the field better. Here, we have added the description with company field.

  1. using GraphQL.Types;  
  2.   
  3. namespace GraphQLInWebApiCore  
  4. {  
  5.     public class EmployeeType : ObjectGraphType<Employee>  
  6.     {  
  7.         public EmployeeType()  
  8.         {  
  9.             Field(a => a.Id);  
  10.             Field(a => a.Name);  
  11.             Field(a => a.Email);  
  12.             Field(a => a.Mobile);  
  13.             Field(a => a.Company).Description("Company Name");  
  14.             Field(a => a.Address);  
  15.             Field(a => a.ShortDescription);  
  16.             Field(a => a.LongDescription);  
  17.         }  
  18.     }  
  19. }  

Once you run the application, in the playground UI, you can see the description for that particular field.

GraphQL In .NET Core Web API With Entity Framework Core 

Now, we might have a question about how we can use GraphQL inside the API and expose through the endpoint.

In order to use GraphQL, we need to add the GraphQL.Client NuGet package.

Create an Employee controller and create one GET method inside that.

Initialize GraphQLClient with GraphQL URL

Create an instance of GraphQLRequest and write the same query which we tried in playground UI.

Call PostAsync method of GraphQLClient and you will get the response.

Convert that response to List of Employees and return it.

  1. using GraphQL.Client;  
  2. using GraphQL.Common.Request;  
  3. using Microsoft.AspNetCore.Mvc;  
  4. using System.Collections.Generic;   
  5. using System.Threading.Tasks;  
  6.   
  7. namespace GraphQLGraphTypeFirstSingleTable.Controllers  
  8. {  
  9.     [Route("Employee")]  
  10.     public class EmployeeController : Controller  
  11.     {  
  12.         [HttpGet]  
  13.         public async Task<List<Employee>> Get()  
  14.         {  
  15.             using (GraphQLClient graphQLClient = new GraphQLClient("http://localhost:64034/graphql"))  
  16.             {  
  17.                 var query = new GraphQLRequest  
  18.                 {  
  19.                     Query = @"   
  20.                         { employees   
  21.                             { name email }   
  22.                         }",  
  23.                 };  
  24.                 var response = await graphQLClient.PostAsync(query);  
  25.                 return response.GetDataFieldAs<List<Employee>>("employees");   
  26.             }  
  27.         }  
  28.     }  
  29. }  

Run the application and open Postman to verify preceding API. Select GET as the method and add the API URL to call the Employee controller GET method.

Click on the "Send" button and you can see the list of employees.

GraphQL In .NET Core Web API With Entity Framework Core 

In this article, we saw how to use GraphQL with one table without argument. In the next part, we will see how we can pass the argument in GraphQL query.

You can download the sample from here.