Repository Pattern In ASP.NET Core MVC And Entity Framework Core


This article introduces the CRUD operations using repository pattern in ASP.NET Core MVC and Entity Framework Core. We create two projects one is a web application for UI and another project is a class library for entities. We create the database from these entities using Entity Framework Core migrations. To keep this article simple and short, we use single entity named Employee to perform CRUD operations.

Why Repository Pattern


We implement repository pattern to develop a loosely coupled application. It makes the code more testable. It creates an abstraction layer between ORM and business logic layer of the application.

Figure 1: Repository Pattern

As per figure 1, the repository mediates between the data source layer (Entity Framework) and the business layer (Controller) of the application. It performs operations as following way.

  1. It queries the underlying data source (database) for the data.
  2. It maps the data from the data source to a business entity that uses to create the database.
  3. It persists changes in the business entity to the data source.

It has some advantages which are as follows.

  1. An entity might have many operations which perform from many locations in the application, so we write logic for common operations in the repository. These operations might be Create, Read, Update, Delete, Search, Filter, Sort, Paging, and Caching etc.
  2. The Entity Framework is not testable out of the box. We have to create mock classes to test it. Data access logic can be tested using repository pattern.
  3. As business logic and data access logic separate in the repository pattern that’s why it easy to manage and readable. It reduces development as well me, as common functionality logic writes once in the application.

We create a new database and implement the repository pattern with Entity Framework Core. Database creates from separate class library.

Create Database


We create a new class library project named RP.Data. We create all entities in this class library project. It uses the Code First approach of Entity Framework Core and SQL Server as a database. We add support for both entity framework core and SQL Server database provider. We have to install two NuGet packages into this project which are

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.SqlServer

Create the Data Model

The application performs CRUD operations on a single entity. We create two entities named BaseEntity and Employee. The BaseEntity class has common properties and will be inherited by each other entities. The BaseEntity class creates as per following code snippet.

The application performs CRUD operations on Employee entity. Now, create Employee class that inherits from the BaseEntity class as per following code snippet.

Now, let’s define a configuration for the Employee entity. Database table will be created using configuration of the Employee entity. The following code snippet for EmployeeMap class.

Now, we create context class named ApplicationContext. It inherits from DbContext. The following code snippet for it.

Database Connectivity using EF

We defined a data model with context. Now, we define a connection between database and context in the web application. We compliance the following procedure to use context in the application.

1. We define a connection string to connect context to the database. Open the appsetting.json file and define connection string as per following code snippet.

2. Application configuration initializes from Startup class. The context injects to MVC controller using constructor dependency injection. Hence, it registers as a service in Startup class. The following code snippet for ConfigureServices method where context registers as a service.

Database Initialize using EF Migration

We use the Entity Framework Core Migration to create a database from the data model. To perform the migration, we can use Command Line Interface (CLI). The Entity Framework Core tools for the CLI are provided in Microsoft.EntityFrameworkCore.Tool.DotNet. To install this package, we can’t use install-package command or package manager GUI. But we can install this package in the application to editing the .csproj file and add this package to the DotNetCliToolReference. The following XML code is added in the RP.Data csproj file.

Now, we install one more NuGet package to perform the migration in this class library project.

Microsoft.EntityFrameworkCore.Design

We create a new class named DesignTimeDbContextFactory in web project for migration initialization. The following code snippet for same.

Now we have to follow steps to create a new database from a data model. These are

  1. Save Changes and build the project.
  2. Open solution location folder. In Solution Explorer, right-click the class library project and choose Open in File Explorer from the context menu.
  3. Write “cmd” command in the address bar and press Enter.

To initiate migration, enter the following command in the command window.

dotnet ef migrations add InitialMigration –s ../RP.Web/

Here –s stands for start up project and RP.Web is directory path where application start up file exists.

Figure 2: Entity Framework Core Migration

Now, we apply the migration to the database. We enter following command in the command window. This command creates database and tables in it.

dotnet ef database update –s ../RP.Web/

Hence, the database has been created using code first approach of Entity Framework Core.

Implement Repository Pattern


ASP.NET Core is designed to support dependency injection. So, we create a repository interface named IEmployeeRepository for Employee entity in the RP.Data project. The following code snippet for it.

Now, let’s implement the preceding interface on a class named EmployeeRepository. This class has definitions of all methods to perform CRUD operations on the Employee entity. It has a parameterized constructor that accepts Context as a parameter. It passes at a time of repository instance creates by dependency injection. The following is a code snippet for the EmployeeRepository class under RP.Data project.

Now, repository and database have been created for the application. As web application communicates to data access layer via an interface so we register repository to the dependency injection during the application start up. The following code is updated code for ConfigureServices method in the Startup class.

Create Application User Interface


Now, we create a view model named EmployeeViewModel for application UI and CRUD operations. This model strongly binds with a view. The following code snippet for it.

Now, we proceed with the controller. We create a controller named EmployeeController under the Controllers folder of the application.

This controller holds all action methods for each user interface to perform the CRUD operations. We create an IEmployeeRepository interface instance then inject it in the controller’s constructor to get an object of EmployeeRepository. The following is a code snippet for the EmployeeController.

As per preceding code, we can notice that the Controller takes theIEmployeeRepository as a constructor parameter. The ASP.NET dependency injection will take care of passing an instance of IEmployeeRepository into EmployeeController.

Now, let’s develop the user interface to perform the CRUD operations on Employee entity. We develop views for adding and editing an employee, listing, and deletion. Let’s see each one by one.

Employee Listing

It is the first view of the application that shows all employees in the listing. It displays employee data in tabular format including add a new employee option. The employee listing has options to edit and delete an employee individually. It is an index view named index.cshtml under Employee folder of Views. The following code snippet for same.

Now, let’s run the application. It makes a GET request for index() action method t and as a response all the employees listed in the UI as in Figure 3.

Figure 3: Employee Listing

Create / Edit Employee View

As create and edit view have same input fields so we create a common view for both named _AddEditEmployee. This view uses the EmployeeViewModel. Let’s define a create/edit employee partial view under Employee folder of Views. The following is the code snippet for _AddEditEmployee.cshtml.

The application performs create/edit and delete operations in the popup and uses Bootstrap model pop up. Once popup opens in the browser, it saves as cache in the browser. To remove from cache and loading data, we create a JavaScript file named employee-index.js as per following code snippet.

Let’s run the application and shows landing page with employee listing. Now, click on either ‘Add Employee’ or ‘Edit’ button in the employee listing. It makes a GET request for AddEditEmployee action method which sends partial view as a response. The following UI shows form for add/edit an employee.

Figure 4: Add an Employee

Delete an Employee

Now, we perform delete operation on each employee. The employee has a delete button in the listing. When a user clicks on delete button against an employee, a confirmation popup shows to ask “Are you want to delete xxx?”. This pop up has two buttons Delete and Cancel. When a user clicks on Delete button of pop up then it makes a HttpPost request that calls the DeleteEmployee action method and deletes the employee. The following is code snippet for _DeleteEmployee.cshtml

Let’s run the application and click on Delete button of listing. It shows confirmation popup as in Figure 5 to delete an employee.

Figure 5: Delete an Employee

Conclusion


This article demonstrated CRUD operations using Repository Pattern in ASP.NET Core MVC with Entity Framework Core Code First approach. The complete source code is available at GitHub, click here to download.