Repository Pattern In ASP.NET Core

Introduction

This article introduces how to implement repository pattern in the ASP.NET Core, using Entity Framework Core. The repository pattern implements in a separate class library project. We will use the "Code First" development approach and create a database from model using migration. We can view this article’s sample on TechNet Gallery. We will create a single entity Student to perform the CRUD operations.

The repository pattern is intended to create an abstraction layer between the data access layer and the business logic layer of an application. It is a data access pattern that prompts a more loosely coupled approach to data access. We create the data access logic in a separate class, or set of classes, called a repository with the responsibility of persisting the application's business model.


Figure 1: Repository Pattern

As per figure 1, the repository mediates between the data source layer and the business layers of the application. It queries the data source for the data, maps the data from the data source to a business entity, and persists changes in the business entity to the data source. A repository separates the business logic from the interactions with the underlying data source. The repository pattern has some advantages which are as follows.

  1. As we can access data source from many locations, so we can apply centrally managed, caching, consistent access rules and logic
  2. As business logic and database access logic are separate, so both can be tested separately.
  3. It provides the code's maintainability and readability by separating business logic from the data or service access logic.

Implement Repository Pattern

First, we create two projects - one is an ASP.NET Core Web Application and another is class library project which are StudentApplication and SA.Data respectively in the solution. The class library (SA.Data) project has data access logic with repository, entities, and context so we install Entity Framework Core in this.

There is an unsupported issue of EF Core 1.0.0-preview2-final with "NETStandard.Library": "1.6.0". So, we have changed the target framework to netstandard1.6 > netcoreapp1.0. We modify the project.json file of SA.Data project to implement Entity Framework Core in this class library project. So the following code snippet for the project.json file after modification.
  1. {  
  2.   "dependencies": {  
  3.     "Microsoft.EntityFrameworkCore.SqlServer""1.0.0",  
  4.     "Microsoft.EntityFrameworkCore.Tools""1.0.0-preview2-final"  
  5.   },  
  6.   "frameworks": {  
  7.     "netcoreapp1.0": {  
  8.       "imports": [ "dotnet5.6""portable-net45+win8" ]  
  9.     }  
  10.   },  
  11.   "tools": {  
  12.     "Microsoft.EntityFrameworkCore.Tools""1.0.0-preview2-final"  
  13.   },  
  14.   "version""1.0.0-*"  
  15. }  
We are working with Entity Framework Code First approach so the project SA.Data contains entities that are needed in the application's database. In this SA.Data project, we create two entities, one is the BaseEntity class that has common properties that will be inherited by each entity and another is Student. Let's see each entity. The following is a code snippet for the BaseEntity class.
  1. using System;  
  2.   
  3. namespace SA.Data  
  4. {  
  5.     public class BaseEntity  
  6.     {  
  7.         public Int64 Id { get; set; }  
  8.         public DateTime AddedDate { get; set; }  
  9.         public DateTime ModifiedDate { get; set; }  
  10.         public string IPAddress { get; set; }  
  11.     }  
  12. }  
Now, we create a Student entity which inherits from the BaseEntity class. The following is a code snippet for the Student entity.
  1. namespace SA.Data  
  2. {  
  3.     public class Student : BaseEntity  
  4.     {  
  5.         public string FirstName { get; set; }  
  6.         public string LastName { get; set; }  
  7.         public string Email { get; set; }  
  8.         public string EnrollmentNo { get; set; }  
  9.     }  
  10. }  
Now, we define the configuration for the Student entity that will be used when the database table will be created by the entity. The following is a code snippet for the Student mapping entity (StudentMap.cs).
  1. using Microsoft.EntityFrameworkCore.Metadata.Builders;  
  2.   
  3. namespace SA.Data  
  4. {  
  5.     public class StudentMap  
  6.     {  
  7.         public StudentMap(EntityTypeBuilder<Student> entityBuilder)  
  8.         {  
  9.             entityBuilder.HasKey(t => t.Id);  
  10.             entityBuilder.Property(t => t.FirstName).IsRequired();  
  11.             entityBuilder.Property(t => t.LastName).IsRequired();  
  12.             entityBuilder.Property(t => t.Email).IsRequired();  
  13.             entityBuilder.Property(t => t.EnrollmentNo).IsRequired();  
  14.         }  
  15.     }  
  16. }  
The SA.Data project also contains DataContext. The ADO.NET Entity Framework Code First data access approach needs to create a data access context class that inherits from the DbContext class, so we create a context class ApplicationContext (ApplicationContext.cs) class. In this class, we override the OnModelCreating() method. This method is called when the model for a context class (ApplicationContext) has been initialized, but before the model has been locked down and used to initialize the context such that the model can be further configured before it is locked down. The following is the code snippet for the context class.
  1. using Microsoft.EntityFrameworkCore;  
  2.   
  3. namespace SA.Data  
  4. {  
  5.     public class ApplicationContext:DbContext  
  6.     {  
  7.         public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options)  
  8.         {  
  9.         }  
  10.         protected override void OnModelCreating(ModelBuilder modelBuilder)  
  11.         {  
  12.             base.OnModelCreating(modelBuilder);  
  13.             new StudentMap(modelBuilder.Entity<Student>());  
  14.         }  
  15.     }  
  16. }  
The DbContext must have an instance of DbContextOptions in order to execute. We will use dependency injection so we pass options via constructor dependency injection.

ASP.NET Core is designed from the ground up to support and leverage dependency injection. So, we create repository interface for student entity so that we can develop loosely coupled applications. The following code snippet for the IStudentRepository interface.
  1. using System.Collections.Generic;  
  2.   
  3. namespace SA.Data  
  4. {  
  5.     public interface IStudentRepository   
  6.     {  
  7.         void SaveStudent(Student student);  
  8.         IEnumerable<Student> GetAllStudents();  
  9.         Student GetStudent(long id);  
  10.         void DeleteStudent(long id);  
  11.         void UpdateStudent(Student student);  
  12.     }  
  13. }  
Now, let's create a repository class to perform CRUD operations on the Student entity which implements IStudentRepository. This repository contains a parameterized constructor with a parameter as Context so when we create an instance of the repository we pass a context so that the entity has the same context. The following is a code snippet for the StudentRepository class under SA.Data project.
  1. using Microsoft.EntityFrameworkCore;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4.   
  5. namespace SA.Data  
  6. {  
  7.     public class StudentRepository : IStudentRepository  
  8.     {  
  9.         private ApplicationContext context;  
  10.         private DbSet<Student> studentEntity;  
  11.         public StudentRepository(ApplicationContext context)  
  12.         {  
  13.             this.context = context;  
  14.             studentEntity = context.Set<Student>();  
  15.         }  
  16.   
  17.   
  18.         public void SaveStudent(Student student)  
  19.         {  
  20.             context.Entry(student).State = EntityState.Added;  
  21.             context.SaveChanges();  
  22.         }  
  23.   
  24.         public IEnumerable<Student> GetAllStudents()  
  25.         {  
  26.             return studentEntity.AsEnumerable();  
  27.         }  
  28.   
  29.         public Student GetStudent(long id)  
  30.         {  
  31.             return studentEntity.SingleOrDefault(s => s.Id == id);  
  32.         }  
  33.         public void DeleteStudent(long id)  
  34.         {  
  35.             Student student = GetStudent(id);  
  36.             studentEntity.Remove(student);  
  37.             context.SaveChanges();  
  38.         }  
  39.         public void UpdateStudent(Student student)  
  40.         {              
  41.             context.SaveChanges();  
  42.         }         
  43.               
  44.     }  
  45. }  
We developed entity and context to create database but we will come to back on this after creating the web application project.

A Web Application Using the Repository Pattern

Now, we create a MVC application (StudentApplication). This is our third project of the application, this project contains user interface for a Student entity's CRUD operations and the controller to do these operations.

As the concept of dependency injection is central to the ASP.NET Core application, so we register both context and repository to the dependency injection during the application start up. So, we register these as a service in the ConfigureServices method in the StartUp class.
  1. public void ConfigureServices(IServiceCollection services)  
  2.         {  
  3.             services.AddMvc();  
  4.             services.AddDbContext<ApplicationContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  
  5.             services.AddTransient<IStudentRepository, StudentRepository>();  
  6.         }  
Here, the DefaultConnection is connection string which defined in appsettings.json file as per following code snippet.
  1. {  
  2.   "ConnectionStrings": {  
  3.     "DefaultConnection""Data Source=DESKTOP-RG33QHE;Initial Catalog=RepoTestDb;User ID=sa; Password=****"  
  4.   },  
  5.   "Logging": {  
  6.     "IncludeScopes"false,  
  7.     "LogLevel": {  
  8.       "Default""Debug",  
  9.       "System""Information",  
  10.       "Microsoft""Information"  
  11.     }  
  12.   }  
  13. }  
Now, we have configured settings to create database so we have time to create a database using migration. We must choose the SA.Data project in the package manager console during the performance of the  following steps.
  1. Tools –> NuGet Package Manager –> Package Manager Console
  2. Run PM> Add-Migration MyFirstMigration to scaffold a migration to create the initial set of tables for our model. If we receive an error stating the term ‘add-migration’ is not recognized as the name of a cmdlet, then close and reopen Visual Studio
  3. Run PM> Update-Database to apply the new migration to the database. Because our database doesn’t exist yet, it will be created for us before the migration is applied.

Create Application User Interface

Now, we proceed to the controller. Create a StudentController under the Controllers folder of the application.

This controller has all ActionResult methods for each user interface of a CRUD operation. We first create a IStudentRepository interface instance then we inject it in the controller's constructor to get its object. The following is a code snippet for the StudentController.

  1. using Microsoft.AspNetCore.Http;  
  2. using Microsoft.AspNetCore.Mvc;  
  3. using SA.Data;  
  4. using StudentApplication.Models;  
  5. using System;  
  6. using System.Collections.Generic;  
  7. using System.Linq;  
  8.   
  9. namespace StudentApplication.Controllers  
  10. {  
  11.     public class StudentController : Controller  
  12.     {  
  13.         private IStudentRepository studentRepository;  
  14.   
  15.         public StudentController(IStudentRepository studentRepository)  
  16.         {  
  17.             this.studentRepository = studentRepository;  
  18.         }  
  19.   
  20.         [HttpGet]  
  21.         public IActionResult Index()  
  22.         {  
  23.             IEnumerable<StudentViewModel> model = studentRepository.GetAllStudents().Select(s => new StudentViewModel  
  24.             {  
  25.                 Id = s.Id,  
  26.                 Name = $"{s.FirstName} {s.LastName}",  
  27.                 EnrollmentNo = s.EnrollmentNo,  
  28.                 Email = s.Email  
  29.             });  
  30.             return View("Index", model);  
  31.         }  
  32.   
  33.         [HttpGet]  
  34.         public IActionResult AddEditStudent(long? id)  
  35.         {  
  36.             StudentViewModel model = new StudentViewModel();  
  37.             if (id.HasValue)  
  38.             {  
  39.                 Student student = studentRepository.GetStudent(id.Value);                if (student != null)  
  40.                 {  
  41.                     model.Id = student.Id;  
  42.                     model.FirstName = student.FirstName;  
  43.                     model.LastName = student.LastName;  
  44.                     model.EnrollmentNo = student.EnrollmentNo;  
  45.                     model.Email = student.Email;  
  46.                 }  
  47.             }  
  48.             return PartialView("~/Views/Student/_AddEditStudent.cshtml", model);  
  49.         }  
  50.         [HttpPost]  
  51.         public ActionResult AddEditStudent(long? id, StudentViewModel model)  
  52.         {  
  53.             try  
  54.             {  
  55.                 if (ModelState.IsValid)  
  56.                 {  
  57.                     bool isNew = !id.HasValue;  
  58.                     Student student = isNew ? new Student  
  59.                     {  
  60.                         AddedDate = DateTime.UtcNow  
  61.                     } : studentRepository.GetStudent(id.Value);  
  62.                     student.FirstName = model.FirstName;  
  63.                     student.LastName = model.LastName;  
  64.                     student.EnrollmentNo = model.EnrollmentNo;  
  65.                     student.Email = model.Email;  
  66.                     student.IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();  
  67.                     student.ModifiedDate = DateTime.UtcNow;  
  68.                     if (isNew)  
  69.                     {  
  70.                         studentRepository.SaveStudent(student);  
  71.                     }  
  72.                     else  
  73.                     {  
  74.                         studentRepository.UpdateStudent(student);  
  75.                     }                      
  76.                 }  
  77.             }  
  78.             catch (Exception ex)  
  79.             {  
  80.                 throw ex;  
  81.             }  
  82.             return RedirectToAction("Index");  
  83.         }  
  84.   
  85.         [HttpGet]  
  86.         public IActionResult DeleteStudent(long id)  
  87.         {  
  88.             Student student = studentRepository.GetStudent(id);  
  89.             StudentViewModel model = new StudentViewModel  
  90.             {  
  91.                 Name = $"{student.FirstName} {student.LastName}"  
  92.             };  
  93.             return PartialView("~/Views/Student/_DeleteStudent.cshtml", model);  
  94.         }  
  95.         [HttpPost]  
  96.         public IActionResult DeleteStudent(long id, FormCollection form)  
  97.         {  
  98.             studentRepository.DeleteStudent(id);  
  99.             return RedirectToAction("Index");  
  100.         }  
  101.     }  
  102. }  
We can notice that the Controller takes the IStudentRepository as a constructor parameter. The ASP.NET dependency injection will take care of passing an instance of IStudentRepository into student controller. The controller is developed to handle CURD operation requests for the Student entity. Now, let's develop the user interface for the CRUD operations. We develop it for the views for adding and editing a student, a student listing, student deletion. Let's see each one by one.

Student List View

This is the first view when the application is accessed or the entry point of the application is executed. It shows the student listing as in Figure 2. We display student data in tabular format and on this view we create links to add a new student, edit a student and delete a student. This view is an index view and the following is a code snippet for index.cshtml under the Student folder of Views.
  1. @model IEnumerable<StudentViewModel>  
  2. @using StudentApplication.Models  
  3. @using StudentApplication.Code  
  4.   
  5. <div class="top-buffer"></div>  
  6. <div class="panel panel-primary">  
  7.     <div class="panel-heading panel-head">Students</div>  
  8.     <div class="panel-body">  
  9.         <div class="btn-group">  
  10.             <a id="createEditStudentModal" data-toggle="modal" asp-action="AddEditStudent" data-target="#modal-action-student" class="btn btn-primary">  
  11.                 <i class="glyphicon glyphicon-plus"></i>  Add Student  
  12.             </a>  
  13.         </div>  
  14.         <div class="top-buffer"></div>  
  15.         <table class="table table-bordered table-striped table-condensed">  
  16.             <thead>  
  17.                 <tr>  
  18.                     <th>Name</th>                      
  19.                     <th>Email</th>  
  20.                     <th>Enrollment No</th>  
  21.                     <th>Action</th>  
  22.                 </tr>  
  23.             </thead>  
  24.             <tbody>  
  25.                 @foreach (var item in Model)  
  26.                 {  
  27.                     <tr>  
  28.                         <td>@Html.DisplayFor(modelItem => item.Name)</td>  
  29.                         <td>@Html.DisplayFor(modelItem => item.Email)</td>  
  30.                         <td>@Html.DisplayFor(modelItem => item.EnrollmentNo)</td>                         
  31.                         <td>  
  32.                             <a id="editStudentModal" data-toggle="modal" asp-action="AddEditStudent" asp-route-id= "@item.Id" data-target="#modal-action-student"   
  33.                                class="btn btn-info">  
  34.                                 <i class="glyphicon glyphicon-pencil"></i>  Edit  
  35.                             </a>  
  36.                             <a id="deleteStudentModal" data-toggle="modal" asp-action="DeleteStudent" asp-route-id= "@item.Id" data-target="#modal-action-student" class="btn btn-danger">  
  37.                                 <i class="glyphicon glyphicon-trash"></i>  Delete  
  38.                             </a>  
  39.                         </td>  
  40.                     </tr>  
  41.                 }  
  42.             </tbody>  
  43.         </table>  
  44.     </div>  
  45. </div>  
  46.   
  47. @Html.Partial("_Modal"new BootstrapModel { ID = "modal-action-student", AreaLabeledId = "modal-action-student-label", Size = ModalSize.Medium})  
  48.   
  49. @section scripts  
  50. {  
  51.     <script src="~/js/student-index.js" asp-append-version="true"></script>  
  52. }  
When we run the application and call the index() action with a HttpGet request, then we get all the students listed in the UI as in Figure 2. This UI has options for CRUD operations.


Figure 2: Student Listing UI

Create / Edit Student View

We create a common view to create and edit a student so we create a single student view model. The following code snippet for StudentViewModel.cs.
  1. using System.ComponentModel.DataAnnotations;  
  2.   
  3. namespace StudentApplication.Models  
  4. {  
  5.     public class StudentViewModel  
  6.     {  
  7.         public long Id { get; set; }  
  8.         [Display(Name="First Name")]  
  9.         public string FirstName { get; set; }  
  10.         [Display(Name = "Last Name")]  
  11.         public string LastName { get; set; }  
  12.         public string Name { get; set; }   
  13.         public string Email { get; set; }  
  14.         [Display(Name = "Enrollment No")]  
  15.         public string EnrollmentNo { get; set; }  
  16.     }  
  17. }  
We show form in bootstrap modal popup and submit using ajax post; that’s why we create a javascript file which contains method for removing loaded data.
  1. (function ($) {  
  2.     function Student() {  
  3.         var $this = this;  
  4.   
  5.         function initilizeModel() {             
  6.             $("#modal-action-student").on('loaded.bs.modal'function (e) {                 
  7.                 }).on('hidden.bs.modal'function (e) {                     
  8.                     $(this).removeData('bs.modal');  
  9.                 });              
  10.         }         
  11.         $this.init = function () {  
  12.             initilizeModel();  
  13.         }  
  14.     }  
  15.     $(function () {  
  16.         var self = new Student();  
  17.         self.init();          
  18.     })  
  19. }(jQuery))  
Now, define a create/edit student partial view. The following is the code snippet for _AddEditStudent.cshtml.
  1. @model StudentViewModel  
  2. @using StudentApplication.Models  
  3.   
  4. <form asp-action="AddEditStudent" role="form">  
  5.     @await Html.PartialAsync("_ModalHeader"new ModalHeader { Heading =$"{(@Model.Id == 0 ? "Add" : "Edit")} Student"})  
  6.      
  7.     <div class="modal-body form-horizontal">  
  8.         <div class="form-group">  
  9.             <label asp-for="FirstName" class="col-lg-3 col-sm-3 control-label"></label>             
  10.             <div class="col-lg-6">  
  11.                 <input asp-for="FirstName" class="form-control" />                  
  12.             </div>  
  13.         </div>  
  14.         <div class="form-group">  
  15.             <label asp-for="LastName" class="col-lg-3 col-sm-3 control-label"></label>    
  16.             <div class="col-lg-6">  
  17.                 <input asp-for="LastName" class="form-control" />                                 
  18.             </div>  
  19.         </div>  
  20.         <div class="form-group">  
  21.             <label asp-for="Email" class="col-lg-3 col-sm-3 control-label"></label>  
  22.             <div class="col-lg-6">  
  23.                 <input asp-for="Email" class="form-control" />  
  24.             </div>  
  25.         </div>  
  26.         <div class="form-group">  
  27.             <label asp-for="EnrollmentNo" class="col-lg-3 col-sm-3 control-label"></label>   
  28.             <div class="col-lg-6">  
  29.                 <input asp-for="EnrollmentNo" class="form-control" />   
  30.             </div>  
  31.         </div>          
  32.     </div>  
  33.   @await Html.PartialAsync("_ModalFooter"new ModalFooter { })  
  34. </form>  
Now, run the application and click on Edit button of listing which calls AddEditStudent action method, then we get the UI as in Figure 3 to edit a student.


Figure 3: Edit Student UI

Delete A Student

To delete a student, we follow the process of clicking on the Delete button that exists in the Student listing data then a modal popup shows to ask “Are you sure you want to delete xxx?” after clicking on the Delete button that exists in the popup view such as in Figure 4 then it makes a HttpPost request that calls the DeleteStudent() action method and deletes the student. The following is a code snippet for _DeleteStudent.cshtml.
  1. @model StudentViewModel  
  2. @using StudentApplication.Models  
  3.   
  4. @using (Html.BeginForm())  
  5. {  
  6.     @Html.Partial("_ModalHeader"new ModalHeader { Heading = "Delete Student" })  
  7.   
  8.     <div class="modal-body form-horizontal">  
  9.         Are you want to delete @Model.Name?  
  10.     </div>  
  11.     @Html.Partial("_ModalFooter"new ModalFooter { SubmitButtonText = "Delete" })  
  12. }  
Now, run the application and click on Delete button of listing which call DeleteStudent action method, then we get the UI as in Figure 4 to delete a student.


Figure 4: Delete Student UI

Download

You can download complete source code from TechNet Gallery using following links.
  1. Repository Pattern in ASP.NET Core
  2. CRUD Operations in ASP.NET Core and Entity Framework Core
  3. Rating Star Application in ASP.NET Core

See Also

I would recommend more articles which describes the ASP.NET Core application development with the Entity Framework Core.

  1. Overview Of ASP.NET Core
  2. CRUD Operations in ASP.NET Core using Entity Framework Core Code First
  3. Repository Pattern in ASP.NET Core

Conclusion

This article introduced the repository pattern in the ASP.NET Core, using Entity Framework Core with "code first" development approach. We used bootstrap CSS and JavaScript for the user interface design in this application. What do you think about this article?

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now