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

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.

Read the other parts here:

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.

USE [GraphQLDemo]  
/****** Object:  Table [dbo].[Employee]    Script Date: 2/2/2019 9:15:36 PM ******/  
CREATE TABLE [dbo].[Employee](  
    [Id] [bigint] IDENTITY(1,1) NOT NULL,  
    [Name] [varchar](100) NULL,  
    [Email] [varchar](50) NULL,  
    [Mobile] [<