Repository Patterns in C# or MVC Core?

Repository Patterns :- Repository Patterns is a Software Design Pattern and widely used in software developments. It provides abstraction of database operations from other software components or we can say that it is a Abstraction of Data Access Layer.

Using the Repository Patterns we can hide the details of how data is manipulated from underlying datasource into the application. It simply means we have to write the data manipulation logic into the seperate repository that we can change easily when data source is changed for the application then only we have to write the logic in single place.
With Repository Patterns we can easily enables the future changes and applied it in very easy way without more modifications of existing code that is written in data access layer..

To implement Repository Pattern we have to follow below steps :-

  • Create a Interface Repository in which declare the data manipulation methods.
  • Create a service class and implement the Interface into this Service class and provides the complete implementation to methods that is declared in Interface Repository and used for Data Manipulation operations from different data sources.
  • Create a Constructor into the Controller class and pass the Repository interface as a parameter into the Constructor and create a private readonly property of Interface repository and call the required methods from Service Class.

Practical Implementation for Repository Pattern :- For implementing the Repository Pattern in application firstly I have created a Interface IEmployee in which i have declare a method GetAllEmployees() and it is returning the List of Employee.So before creation of Interface create a Model Class and named it as Employee as shown in below code snippet.

                
  public class Employee
    {
        [Key]
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }
        public int Salary { get; set; }
        public string Mobile { get; set; }
    }               
                

As shown in above code I have created a Employee Model Class and after it I have created a Interface named it IEmployee that you can find into below code snippet.

                
public interface IEmployee
    {
        List GetAllEmployees();
    }           
                

After creating a Interface now I have created a EmployeeService Class and implements the Interface into it and provides the implementation of GetAllEmployees() Method into this class.

                
 public class EmployeeService : IEmployee
    {
        private readonly MyDBContext _dbContext;
        public EmployeeService(MyDBContext myDBContext)
        {
            _dbContext=myDBContext;
        }
        public List GetAllEmployees()
        {
            List employees = new List();
            employees = _dbContext.Employees.ToList();
            return employees;
        }
    }            
                

After creating the Service Class and Interface we have to register this services into the Program.cs file with any one of the Service Life time methods(like AddScoped,AddSingleton,AddTransient) with Interface and Service class as depicted into the below code example.

                
using DIExamples.Repository;
using DIExamples.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddScoped();
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Employees}/{action=EmployeeList}/{id?}");

app.Run(); 
                 
                

In the above code examples you can find the Repository Patterns implementations ,I am going to explain here in more details.
I have created a Repository Interface and Service class for database access layer abstraction. In EmployeeService class I have created a Method that is fetching all the employees from database and returning a Employee List and again this services we are going to use in Controller class so it is providing the complete loosely coupled system.Below code is attached for Employee Controller class.

                
 public class EmployeeController : Controller
    {
        private readonly IEmployee emp;
        public EmployeeController(IEmployee employee)
        {
            emp= employee;
        }
        [HttpGet]
        public IActionResult EmployeesList()
        {
            List empList=emp.GetAllEmployees();
            return View(empList);
        }
    }           
                

Below is some screen images that I have attached for your reference and with these images you can easily understand the steps that we required for implementing the Repository Pattern and example code also. Below is the image for Employee Service Class.

Image is not available

Image of Program.cs file using the AddScoped services.

Image is not available

Image of Controller Class having a Constructor and Repository Interface is passed as a parameter.

Image is not available

Image of code for cshtml file that is used for representing the Employee data.

Image is not available

Image of final View that is used for representing the Employee data.

Image is not available

Note :- In the above code example I did not included the Migration Process for creating the database entities from Model Class, you can use the EntityFrameworkCore Code first approach. If you are not aware about the migration process then you can find it below.

Add the connection string into the appSettings.JSON file as shown in below image in which CorePracticeDB is the name of the database we want to create for our application.Here we have used local server you can change it by your server name or IP address.

Image is not available

Create a DBContext Class and add Employee as a DbSet and then run the migration commands.In the below code you can find the complete DBContext class.

                
public class MyDBContext :DbContext
    {
        public MyDBContext(DbContextOptions options):base(options)
        {

        }
        public DbSet Employees { get; set; }
    }          
                
Image is not available
Image is not available

Image is not available

About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server, EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.