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

In this article, we will see how we can load all the children of a parent class using DataLoader.

Consider a scenario where you have around 200 employees and you want to fetch certificates for each employee and the GetCertifications method expects EmployeeId. That means for each employee, we must call the GetCertifications method. Well, that is not a best practice. So, let’s see how DataLoader will be useful in GraphQL to fetch the data in batches.

In order to enable DataLoader, add the below-highlighted line of code under ConfigureServices in Startup.cs.

GraphQL In .NET Core Web API With Entity Framework Core 

Now, modify your existing GetCertificationByEmployee method. Previously we were expected to give EmployeeId, now change it to EmployeeIds, i.e., IEnumerable of long and fetch the data of certifications from DbContext accordingly.

  1. using System.Collections.Generic;  
  2. using System.Linq;  
  3. using System.Threading.Tasks;  
  4.   
  5. namespace GraphQLInWebApiCore  
  6. {  
  7.     public interface ICertificaationRepository  
  8.     {  
  9.         Task<ILookup<long, Certification>> GetCertificationByEmployee(IEnumerable<long> employeeIds);  
  10.     }  
  11. }  
  12.   
  13. using Microsoft.EntityFrameworkCore;  
  14. using System.Collections.Generic;  
  15. using System.Linq;  
  16. using System.Threading.Tasks;  
  17. using System;  
  18.   
  19. namespace GraphQLInWebApiCore  
  20. {  
  21.     public class CertificationRepository : ICertificaationRepository  
  22.     {  
  23.         private readonly GraphQLDemoContext _context;  
  24.         public CertificationRepository(GraphQLDemoContext context)  
  25.         {  
  26.             _context = context;  
  27.         }  
  28.   
  29.         public async Task<ILookup<long, Certification>> GetCertificationByEmployee(IEnumerable<long> employeeIds)  
  30.         {  
  31.             var reviews = await _context.Certification.Where(a => employeeIds.Contains(a.EmployeeId)).ToListAsync();  
  32.             return reviews.ToLookup(r => r.EmployeeId);  
  33.         }  
  34.     }  
  35. }  

Previously, we added a field of type EmployeeCertificationType as below.

  1. Field<ListGraphType<EmployeeCertificationType>>(  
  2.                 "certifications",  
  3.                 resolve: context => certificationRepository.GetCertificationByEmployee(context.Source.Id)  
  4.                 );  

Now, we need to create a BatchLoader using DataLoaderContextAccessor and call LoadAsync to load the certification data.

  1. using GraphQL.DataLoader;  
  2. using GraphQL.Types;  
  3.   
  4. namespace GraphQLInWebApiCore  
  5. {  
  6.     public class EmployeeType : ObjectGraphType<Employee>  
  7.     {  
  8.         public EmployeeType(ICertificaationRepository certificationRepository, IDataLoaderContextAccessor dataLoaderContextAccessor)  
  9.         {  
  10.         …  
  11.             Field<ListGraphType<EmployeeCertificationType>>(  
  12.                 "certifications",  
  13.                 resolve: context =>  
  14.                 {  
  15.                     var loader = dataLoaderContextAccessor.Context.GetOrAddCollectionBatchLoader<long, Certification>(  
  16.                         "GetCertificationByEmployee", certificationRepository.GetCertificationByEmployee);  
  17.   
  18.                     return loader.LoadAsync(context.Source.Id);  
  19.                 });  
  20.         }  
  21.     }  
  22. }  

Run the application and execute the same query which we have executed in the previous article. You can see the result, i.e., all employees with their certifications.

GraphQL In .NET Core Web API With Entity Framework Core 

Let’s expose the same thing from the Web API. Add a GraphQL.Client NuGet package.

In the existing Get method of EmployeeController, just change the query. You can copy paste the query which we executed in the playground UI.

  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 GraphQLGraphTypeFirstNestedTableDataLoader.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:64666/graphql"))  
  16.             {  
  17.                 var query = new GraphQLRequest  
  18.                 {  
  19.                     Query = @"   
  20.                         { employees   
  21.                             { name   
  22.                               email    
  23.                               certifications  
  24.                                  { title }  
  25.                             }  
  26.                         }",  
  27.                 };  
  28.                 var response = await graphQLClient.PostAsync(query);  
  29.                 return response.GetDataFieldAs<List<Employee>>("employees");  
  30.             }  
  31.         }  
  32.     }  
  33. }  

As we are exposing Employee model from API, we need to add a list of certifications as one of the properties in Employee.

  1. using System.Collections.Generic;  
  2.   
  3. namespace GraphQLGraphTypeFirstNestedTableDataLoader  
  4. {  
  5.     public partial class Employee  
  6.     {  
  7.         …  
  8.        public List<Certification> certifications { getset; }  
  9.     }  
  10. }  

Run the application, copy the URL from the browser, append with /Employee, and click on the "Send" button.

You can see all the employees with their certifications.

GraphQL In .NET Core Web API With Entity Framework Core 

So far, we have seen the simple use of GraphQL with single and multiple tables with arguments and how we can expose through Web API. In the next article, we will see how we can write different kinds of queries in GraphQL.

You can download sample from here.