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

In the previous article, we have seen how we can make a GraphQL query on Employees and select the columns in which we would like to have a response. Today, we will see how we can declare a parameter, and with the same parameter value, how we can query and get the result accordingly.

We will use the same application which we have created in our previous article. So, add one more method in the repository called GetEmployeeById which expects employeeId as long.

IEmployeeRepository

using System.Collections.Generic;
using System.Threading.Tasks;

namespace GraphQLInWebApiCore
{
    public interface IEmployeeRepository
    {
        Task<Employee> GetEmployeeById(long id);
    }
}

EmployeeRepository

using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GraphQLInWebApiCore
{
    public class EmployeeRepository : IEmployeeRepository
    {
        // Other code...
        
        public Task<Employee> GetEmployeeById(long id)
        {
            return _context.Employee.SingleAsync(a => a.Id == id);
        }
    }
}

In GraphQL implementation, we need to modify the query part, only as we haven’t changed any field in Employee, the schema will be the same to resolve the EmployeeQuery.

EmployeeQuery

In the query, we need to add one more field of type EmployeeType. We need to add the argument value. For that, we need to initialize QueryArguments which actually expects QueryArgument of type NonNullGraphType of IdGraphType. Then, we provide the argument name as id. Now at the time of resolving the context, pass the same ID to the repository method which actually returns the employee details having that ID.

EmployeeQuery

using GraphQL.Types;

namespace GraphQLInWebApiCore
{
    public class EmployeeQuery : ObjectGraphType
    {
        public EmployeeQuery(IEmployeeRepository employeeRepository)
        {
            Field<EmployeeType>(
                "employee",
                arguments: new QueryArguments(new QueryArgument<NonNullGraphType<IdGraphType>>
                { Name = "id" }),
                resolve: context =>
                {
                    var id = context.GetArgument<int>("id");
                    return employeeRepository.GetEmployeeById(id);
                }
            );
        }
    }
}

Run the application and in the query, we need to pass the argument; i.e., id. Here, for example, we have passed id:1. And on the right side, we can see that we get only one employee having id as 1.

Run the application

Now, in order to use GraphQL in API, add GraphQL.Client NuGet package.

Create one more "Get" method in EmployeeController with parameter id.

Initialize GraphQLClient with GraphQL URL

Create an instance of GraphQLRequest and write the same query that we tried in the playground UI inside that. Along with the query, declare the employeeId variable and set it with the value passed in the API.

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

Convert that response to Employee type and return it.

using GraphQL.Client;
using GraphQL.Common.Request;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace GraphQLGraphTypeFirstSingleTableArgument.Controllers
{
    [Route("Employee")]
    public class EmployeeController : Controller
    {
        [HttpGet("{id}")]
        public async Task<Employee> Get(int id)
        {
            using (GraphQLClient graphQLClient = new GraphQLClient("http://localhost:64925/graphql"))
            {
                var query = new GraphQLRequest
                {
                    Query = @"
                        query employeeQuery($employeeId: ID!)
                        { 
                            employee(id: $employeeId)   
                            { 
                                id name email 
                            } 
                        }",
                    Variables = new { employeeId = id }
                };
                var response = await graphQLClient.PostAsync(query);
                return response.GetDataFieldAs<Employee>("employee");
            }
        }
    }
}

Run the application and copy the URL from the browser. Open the Postman application, paste the copied URL, append with Employee/1, and click on the "Send" button.

You can see the employee details having id=1.

Employee details

So far, we have seen queries with only one table. In the next article, we will see how to configure GraphQL for multiple tables, like parent-child relationships.

You can download the sample from here.


Similar Articles