Loading, please wait...

A to Z Full Forms and Acronyms

Repository Pattern in ASP.NET Core REST API.

In this article, we will learnWhat is Repository PatternBenefits of Repository PatternAn example that uses a repository pattern to store and retrieve data from the SQL server database.

Repository Pattern in ASP.NET Core REST API

Repository Pattern

Repository Pattern is a reflection of the Data Access Layer. It conceals the subtleties of how precisely the data is spared or recovered from the fundamental data source. The subtleties of how the data is put away and recovered are in the separate repository. For instance, you may have a repository that stores and recovers data from an in-memory assortment. You may have another repository that stores and recovers data from a database like SQL Server. One more repository that stores and recovers data from an XML record.

Repository Pattern Interface

The interface in the repository pattern determines

Tasks supported by the repository are:

The data required for every one of the activities i.e the boundaries that should be passed to the technique and the data the strategy returns

The repository interface contains what it can do, however not, how it does, what it can do

The execution subtleties are in the separate repository class that actualizes the Repository Interface.

public interface IEmployeeRepository
{
    Task<IEnumerable<Employee>> GetEmployees();
    Task<Employee> GetEmployee(int employeeId);
    Task<Employee> AddEmployee(Employee employee);
    Task<Employee> UpdateEmployee(Employee employee);
    void DeleteEmployee(int employeeId);
}

IEmployeeRepository interface underpins the accompanying tasks

Get all the workers: Get all the employees

Get a solitary worker by id: Get a single employee by id

Include another representative: Add a new employee

Update a worker: Update an employee

Erase a worker: Delete an employee

The subtleties of how these activities are executed are in the repository class that actualizes this IEmployeeRepository interface.

Repository Pattern - SQL Server Implementation

The accompanying EmployeeRepository class gives execution to IEmployeeRepository. This particular usage stores and recovers workers from a SQL worker database. With the accompanying 2 lines of code, ASP.NET Core gives an occasion of EmployeeRepository class when an example of IEmployeeRepository is mentioned. So also, a case of DepartmentRepository class is given when a case of IDepartmentRepository is mentioned.

using EmployeeManagement.Models;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace EmployeeManagement.Api.Models
{
    public class EmployeeRepository : IEmployeeRepository
    {
        private readonly AppDbContext appDbContext;

        public EmployeeRepository(AppDbContext appDbContext)
        {
            this.appDbContext = appDbContext;
        }

        public async Task<IEnumerable<Employee>> GetEmployees()
        {
            return await appDbContext.Employees.ToListAsync();
        }

        public async Task<Employee> GetEmployee(int employeeId)
        {
            return await appDbContext.Employees
                .FirstOrDefaultAsync(e => e.EmployeeId == employeeId);
        }

        public async Task<Employee> AddEmployee(Employee employee)
        {
            var result = await appDbContext.Employees.AddAsync(employee);
            await appDbContext.SaveChangesAsync();
            return result.Entity;
        }

        public async Task<Employee> UpdateEmployee(Employee employee)
        {
            var result = await appDbContext.Employees
                .FirstOrDefaultAsync(e => e.EmployeeId == employee.EmployeeId);

            if (result != null)
            {
                result.FirstName = employee.FirstName;
                result.LastName = employee.LastName;
                result.Email = employee.Email;
                result.DateOfBrith = employee.DateOfBrith;
                result.Gender = employee.Gender;
                result.DepartmentId = employee.DepartmentId;
                result.PhotoPath = employee.PhotoPath;

                await appDbContext.SaveChangesAsync();

                return result;
            }

            return null;
        }

        public async void DeleteEmployee(int employeeId)
        {
            var result = await appDbContext.Employees
                .FirstOrDefaultAsync(e => e.EmployeeId == employeeId);
            if (result != null)
            {
                appDbContext.Employees.Remove(result);
                await appDbContext.SaveChangesAsync();
            }
        }
    }
}

DepartmentRepository Interface

public interface IDepartmentRepository
{
    IEnumerable<Department> GetDepartments();
    Department GetDepartment(int departmentId);
}

DepartmentRepository Implementation

using EmployeeManagement.Models;
using System.Collections.Generic;
using System.Linq;

namespace EmployeeManagement.Api.Models
{
    public class DepartmentRepository : IDepartmentRepository
    {
        private readonly AppDbContext appDbContext;

        public DepartmentRepository(AppDbContext appDbContext)
        {
            this.appDbContext = appDbContext;
        }

        public Department GetDepartment(int departmentId)
        {
            return appDbContext.Departments
                .FirstOrDefault(d => d.DepartmentId == departmentId);
        }

        public IEnumerable<Department> GetDepartments()
        {
            return appDbContext.Departments;
        }
    }
}

Which usage to utilize

With the accompanying 2 lines of code, ASP.NET Core gives a case of EmployeeRepository class when an occurrence of IEmployeeRepository is mentioned. Correspondingly an occasion of DepartmentRepository class is given when a case of IDepartmentRepository is mentioned.

public void ConfigureServices(IServiceCollection services)
{
    // Rest of the code
    services.AddScoped<IDepartmentRepository, DepartmentRepository>();
    services.AddScoped<IEmployeeRepository, EmployeeRepository>();
}

We are utilizing AddScoped() strategy since we need the example to be alive and accessible for the whole extent of the given HTTP demand. For another new HTTP demand, another case of EmployeeRepository class will be given and it will be accessible all through the whole extent of that HTTP demand.

All through our whole application, in all the spots where IEmployeeRepository has infused an occurrence of EmployeeRepository is given. In the event that you need your application to utilize an alternate execution rather, all you have to change is the accompanying one line of code.

Advantages of Repository Pattern

The code is cleaner and simpler to reuse and keep up.

Empowers us to make inexactly coupled frameworks. For instance, on the off chance that we need our application to work with prophet rather than SQL Server, actualize an OracleRepository that realizes how to peruse and keep in touch with the Oracle database and register OracleRepository with the reliance infusion framework.

In a unit testing venture, it is anything but difficult to supplant a genuine repository with a phony usage for testing.

A to Z Full Forms and Acronyms