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

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.

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.


using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
 
namespace GraphQLInWebApiCore  
{  
 public interface ICertificaationRepository  
    {  
        Task<ILookup<long, Certification>> GetCertificationByEmployee(IEnumerable<long> employeeIds);  
    }  
}  
 
using Microsoft.EntityFrameworkCore;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
using System;  
 
namespace GraphQLInWebApiCore  
{  
 public class CertificationRepository : ICertificaationRepository  
    {  
 private readonly GraphQLDemoContext _context;  
 public CertificationRepository(GraphQLDemoContext context)  
        {  
            _context = context;  
        }  
 
 public async Task<ILookup<long, Certification>> GetCertificationByEmployee(IEnumerable<long> employeeIds)  
        {  
            var reviews = await _context.Certification.Where(a => employeeIds.Contains(a.EmployeeId)).ToListAsync();  
 return reviews.ToLookup(r => r.EmployeeId);  
        }  
    }  
}  

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