Generic Repository Pattern In ASP.NET Core

Introduction

This article introduces how to implement generic repository pattern in ASP.NET Core, using Entity Framework Core. The generic repository pattern implements in a separate class library project. It uses the "Code First" development approach and creates a database from a model, using migration. This article demonstrates a sample Application, which has one to many relationship in ASP.NET Core with Entity Framework Core. The Application source code is available for download on MSDN sample https://code.msdn.microsoft.com/Generic-Repository-Pattern-f133bca4).

The repository pattern is intended to create an Abstraction layer between the Data Access layer and Business Logic layer of an Application. It is a data access pattern that prompts a more loosely coupled approach to data access. We create a generic repository, which 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.

Implement Generic Repository Pattern

To implement generic repository pattern, create two projects - one is an ASP.NET Core Web Application and another is a class library project, which are GR.Web and GR.Data respectively in the solution. The class library is named as SA.Data project, which has data access logic with generic repository, entities and context, so we install Entity Framework Core in this project.

There is an unsupported issue of EF Core 1.0.0-preview2-final with "NETStandard.Library": "1.6.0". Thus, we have changed the target framework to netstandard1.6 > netcoreapp1.0. We modify the project.json file of GR.Data project to implement Entity Framework Core in this class library project. Thus, the code snippet, mentioned below 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. }  
This Application uses the Entity Framework Code First approach, so the project GR.Data contains entities that are required in the Application's database. The GR.Data project holds three entities, one is the BaseEntity class that has common properties that will be inherited by each entity. The code snippet, mentioned below is for the BaseEntity class.
  1. using System;  
  2. namespace GR.Data {  
  3.     public class BaseEntity {  
  4.         public Int64 Id {  
  5.             get;  
  6.             set;  
  7.         }  
  8.         public DateTime AddedDate {  
  9.             get;  
  10.             set;  
  11.         }  
  12.         public DateTime ModifiedDate {  
  13.             get;  
  14.             set;  
  15.         }  
  16.         public string IPAddress {  
  17.             get;  
  18.             set;  
  19.         }  
  20.     }  
  21. }  
The Author and Book entities have one to many relationship, as shown below.

enties
Author-Book Relationship

Now, we create an Author entity, which is inherited from BaseEntity class. The code snippet, mentioned below is for the Author entity.
  1. using System.Collections.Generic;  
  2. namespace GR.Data {  
  3.     public class Author: BaseEntity {  
  4.         public string FirstName {  
  5.             get;  
  6.             set;  
  7.         }  
  8.         public string LastName {  
  9.             get;  
  10.             set;  
  11.         }  
  12.         public string Email {  
  13.             get;  
  14.             set;  
  15.         }  
  16.         public virtual ICollection < Book > Books {  
  17.             get;  
  18.             set;  
  19.         }  
  20.     }  
  21. }  
Now, we define the configuration for the Author entity that will be used when the database table will be created by the entity. The following is a code snippet for the Author mapping entity (AuthorMap.cs).
  1. using Microsoft.EntityFrameworkCore.Metadata.Builders;  
  2. namespace GR.Data {  
  3.     public class AuthorMap {  
  4.         public AuthorMap(EntityTypeBuilder < Author > entityBuilder) {  
  5.             entityBuilder.HasKey(t => t.Id);  
  6.             entityBuilder.Property(t => t.FirstName).IsRequired();  
  7.             entityBuilder.Property(t => t.LastName).IsRequired();  
  8.             entityBuilder.Property(t => t.Email).IsRequired();  
  9.         }  
  10.     }  
  11. }  
Now, we create a Book entity, which inherits from the BaseEntity class. The code snippet, mentioned below is for the Book entity.
  1. using System;  
  2. namespace GR.Data {  
  3.     public class Book: BaseEntity {  
  4.         public Int64 AuthorId {  
  5.             get;  
  6.             set;  
  7.         }  
  8.         public string Name {  
  9.             get;  
  10.             set;  
  11.         }  
  12.         public string ISBN {  
  13.             get;  
  14.             set;  
  15.         }  
  16.         public string Publisher {  
  17.             get;  
  18.             set;  
  19.         }  
  20.         public virtual Author Author {  
  21.             get;  
  22.             set;  
  23.         }  
  24.     }  
  25. }  
Now, we define the configuration for the Book entity that will be used when the database table will be created by the entity. The code snippet is mentioned below for the Book mapping entity (BookMap.cs).
  1. using Microsoft.EntityFrameworkCore.Metadata.Builders;  
  2. namespace GR.Data {  
  3.     public class BookMap {  
  4.         public BookMap(EntityTypeBuilder < Book > entityBuilder) {  
  5.             entityBuilder.HasKey(t => t.Id);  
  6.             entityBuilder.Property(t => t.Name).IsRequired();  
  7.             entityBuilder.Property(t => t.ISBN).IsRequired();  
  8.             entityBuilder.Property(t => t.Publisher).IsRequired();  
  9.             entityBuilder.HasOne(e => e.Author).WithMany(e => e.Books).HasForeignKey(e => e.AuthorId);  
  10.         }  
  11.     }  
  12. }  
The GR.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. namespace GR.Data {  
  3.     public class ApplicationContext: DbContext {  
  4.         public ApplicationContext(DbContextOptions < ApplicationContext > options): base(options) {}  
  5.         protected override void OnModelCreating(ModelBuilder modelBuilder) {  
  6.             base.OnModelCreating(modelBuilder);  
  7.             new AuthorMap(modelBuilder.Entity < Author > ());  
  8.             new BookMap(modelBuilder.Entity < Book > ());  
  9.         }  
  10.     }  
  11. }  
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 to support and leverage dependency injection. Thus, we create generic repository interface for the entity operations,  so that we can develop loosely coupled Applications. The code snippet, mentioned below is for the IRepository interface.
  1. using System.Collections.Generic;  
  2. namespace GR.Data {  
  3.     public interface IRepository < T > where T: BaseEntity {  
  4.         IEnumerable < T > GetAll();  
  5.         T Get(long id);  
  6.         void Insert(T entity);  
  7.         void Update(T entity);  
  8.         void Delete(T entity);  
  9.     }  
  10. }  
Now, let's create a repository class to perform CRUD operations on the entity,  which implements IRepository. 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 code snippet is mentioned below for the Repository class under GR.Data project.
  1. using Microsoft.EntityFrameworkCore;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. namespace GR.Data {  
  6.     public class Repository < T > : IRepository < T > where T: BaseEntity {  
  7.         private readonly ApplicationContext context;  
  8.         private DbSet < T > entities;  
  9.         string errorMessage = string.Empty;  
  10.         public Repository(ApplicationContext context) {  
  11.             this.context = context;  
  12.             entities = context.Set < T > ();  
  13.         }  
  14.         public IEnumerable < T > GetAll() {  
  15.             return entities.AsEnumerable();  
  16.         }  
  17.         public T Get(long id) {  
  18.             return entities.SingleOrDefault(s => s.Id == id);  
  19.         }  
  20.         public void Insert(T entity) {  
  21.             if (entity == null) {  
  22.                 throw new ArgumentNullException("entity");  
  23.             }  
  24.             entities.Add(entity);  
  25.             context.SaveChanges();  
  26.         }  
  27.         public void Update(T entity) {  
  28.             if (entity == null) {  
  29.                 throw new ArgumentNullException("entity");  
  30.             }  
  31.             context.SaveChanges();  
  32.         }  
  33.         public void Delete(T entity) {  
  34.             if (entity == null) {  
  35.                 throw new ArgumentNullException("entity");  
  36.             }  
  37.             entities.Remove(entity);  
  38.             context.SaveChanges();  
  39.         }  
  40.     }  
  41. }  
We developed entity and context which are required to create a database but we will come back to this after creating the Web Application project.

A Web Application Using the Generic Repository Pattern

Now, we create a MVC Application (GR.Web). This is our second project of the Application. This project contains user interface for both author and book entities database operations and the controller to do these operations.

As the concept of dependency injection is central to the ASP.NET Core Application, we register both context and repository to the dependency injection during the Application start up. Thus, we register these as a Service in the ConfigureServices method in the StartUp class.
  1. public void ConfigureServices(IServiceCollection services) {  
  2.     // Add framework services.  
  3.     services.AddApplicationInsightsTelemetry(Configuration);  
  4.     services.AddMvc();  
  5.     services.AddDbContext < ApplicationContext > (options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  
  6.     services.AddScoped(typeof(IRepository < > ), typeof(Repository < > ));  
  7. }  
  8.  
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=GRepoDb;User ID=sa; Password=*****"    
  4.     },    
  5.     "ApplicationInsights": {    
  6.         "InstrumentationKey"""    
  7.     },    
  8.     "Logging": {    
  9.         "IncludeScopes"false,    
  10.         "LogLevel": {    
  11.             "Default""Debug",    
  12.             "System""Information",    
  13.             "Microsoft""Information"    
  14.         }    
  15.     }    
  16. }    
Now, we have configured settings to create database, so we have time to create a database, using migration. We must choose the GR.Data project in the Package Manager console during the performance of the steps, mentioned below.
  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. We create two controllers, where one is AuthorController and another is BookController under the Controllers folder of the Application.

These controllers have all ActionResult methods for each user interface of an operation. We create an IRepository interface instance, then we inject it in the controller's constructor to get its object. The following is a partial code snippet for the AuthorController in which repository is injected, using constructor dependency injection.

  1. using GR.Data;  
  2. using GR.Web.Models;  
  3. using Microsoft.AspNetCore.Mvc;  
  4. using System;  
  5. using System.Collections.Generic;  
  6. using System.Linq;  
  7. namespace GR.Web.Controllers {  
  8.     public class AuthorController: Controller {  
  9.         private IRepository < Author > repoAuthor;  
  10.         private IRepository < Book > repoBook;  
  11.         public AuthorController(IRepository < Author > repoAuthor, IRepository < Book > repoBook) {  
  12.             this.repoAuthor = repoAuthor;  
  13.             this.repoBook = repoBook;  
  14.         }  
  15.     }  
  16. }  
We can notice that Controller takes the IRepository as a constructor parameter. ASP.NET dependency injection will take care of passing an instance of IRepository into Author controller. The controller is developed to handle operations requests for both Author and Book entities. Now, let's develop the user interface for the Author Listing, Add Author with Book, Edit Author and Add Book. Let's see each one by one.

Author List View

This is the first view when the Application is accessed or the entry point of the application is executed. It shows the author listing as in Figure 2. The author data is displayed in a tabular format and on this view, it has linked to add a new author with his/her book, edit an author and add a book.

To pass data from controller to view, create named AuthorListingViewModel view model, as per code snippet, mentioned below.
  1. namespace GR.Web.Models {  
  2.     public class AuthorListingViewModel {  
  3.         public long Id {  
  4.             get;  
  5.             set;  
  6.         }  
  7.         public string Name {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public string Email {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public int TotalBooks {  
  16.             get;  
  17.             set;  
  18.         }  
  19.     }  
  20. }  
Now, we create action method, which returns an index view with the data. The code snippet of Index action method in AuthorController is mentioned below.
  1. [HttpGet]  
  2. public IActionResult Index() {  
  3.     List < AuthorListingViewModel > model = new List < AuthorListingViewModel > ();  
  4.     repoAuthor.GetAll().ToList().ForEach(a => {  
  5.         AuthorListingViewModel author = new AuthorListingViewModel {  
  6.             Id = a.Id,  
  7.                 Name = $ "{a.FirstName} {a.LastName}",  
  8.                 Email = a.Email  
  9.         };  
  10.         author.TotalBooks = repoBook.GetAll().Count(x => x.AuthorId == a.Id);  
  11.         model.Add(author);  
  12.     });  
  13.     return View("Index", model);  
  14. }  
Now, we create an index view, as per the code snippet, mentioned below under the Author folder of views.
  1. @model IEnumerable < AuthorListingViewModel > @using GR.Web.Models  
  2. @using GR.Web.Code < div class = "top-buffer" > < /div> < div class = "panel panel-primary" > < div class = "panel-heading panel-head" > Authors < /div> < div class = "panel-body" > < div class = "btn-group" > < a id = "createEditAuthorModal"  
  3. data - toggle = "modal"  
  4. asp - action = "AddAuthor"  
  5. data - target = "#modal-action-author"  
  6. class = "btn btn-primary" > < i class = "glyphicon glyphicon-plus" > < /i> Add Author < /a> < /div> < div class = "top-buffer" > < /div> < table class = "table table-bordered table-striped table-condensed" > < thead > < tr > < th > Name < /th> < th > Email < /th> < th > Total Books < /th> < th > Action < /th> < /tr> < /thead> < tbody > @foreach(var item in Model) { < tr > < td > @Html.DisplayFor(modelItem => item.Name) < /td> < td > @Html.DisplayFor(modelItem => item.Email) < /td> < td > @Html.DisplayFor(modelItem => item.TotalBooks) < /td> < td > < a id = "editAuthorModal"  
  7.     data - toggle = "modal"  
  8.     asp - action = "EditAuthor"  
  9.     asp - route - id = "@item.Id"  
  10.     data - target = "#modal-action-author"  
  11.     class = "btn btn-info" > < i class = "glyphicon glyphicon-pencil" > < /i> Edit < /a> < a id = "addBookModal"  
  12.     data - toggle = "modal"  
  13.     asp - action = "AddBook"  
  14.     asp - route - id = "@item.Id"  
  15.     data - target = "#modal-action-author"  
  16.     class = "btn btn-success" > < i class = "glyphicon glyphicon-book" > < /i> Book < /a> < /td> < /tr>  
  17. } < /tbody> < /table> < /div> < /div>  
  18. @Html.Partial("_Modal"new BootstrapModel {  
  19.     ID = "modal-action-author", AreaLabeledId = "modal-action-author-label", Size = ModalSize.Large  
  20. })  
  21. @section scripts { < script src = "~/js/author-index.js"  
  22.     asp - append - version = "true" > < /script>  
  23. }  
  24. It shows all forms in bootstrap model popup so create the author - index.js file as per following code snippet.  
  25.     (function($) {  
  26.         function Author() {  
  27.             var $this = this;  
  28.   
  29.             function initilizeModel() {  
  30.                 $("#modal-action-author").on('loaded.bs.modal'function(e) {}).on('hidden.bs.modal'function(e) {  
  31.                     $(this).removeData('bs.modal');  
  32.                 });  
  33.             }  
  34.             $this.init = function() {  
  35.                 initilizeModel();  
  36.             }  
  37.         }  
  38.         $(function() {  
  39.             var self = new Author();  
  40.             self.init();  
  41.         })  
  42.     }(jQuery))  
When we run the Application and call the index() action method from AuthorController with a HttpGet request, we get all the authors listed in the UI, as shown in Figure 2.

enties
Author Listing

Add Author

To pass the data from UI to controller to add an author with his/her book, define view model named AuthorBookViewModel, as per the code snippet, mentioned below.
  1. using System.ComponentModel.DataAnnotations;  
  2. namespace GR.Web.Models {  
  3.     public class AuthorBookViewModel {  
  4.         public long Id {  
  5.             get;  
  6.             set;  
  7.         }  
  8.         [Display(Name = "First Name")]  
  9.         public string FirstName {  
  10.             get;  
  11.             set;  
  12.         }  
  13.         [Display(Name = "Last Name")]  
  14.         public string LastName {  
  15.             get;  
  16.             set;  
  17.         }  
  18.         public string Email {  
  19.             get;  
  20.             set;  
  21.         }  
  22.         [Display(Name = "Book Name")]  
  23.         public string BookName {  
  24.             get;  
  25.             set;  
  26.         }  
  27.         public string ISBN {  
  28.             get;  
  29.             set;  
  30.         }  
  31.         public string Publisher {  
  32.             get;  
  33.             set;  
  34.         }  
  35.     }  
  36. }  
The AuthorController has an action method named AddAuthor, which returns view to add an author. The code snippet is mentioned below is for same action method for both GET and Post requests.
  1. [HttpGet]  
  2. public PartialViewResult AddAuthor() {  
  3.         AuthorBookViewModel model = new AuthorBookViewModel();  
  4.         return PartialView("_AddAuthor", model);  
  5.     }  
  6.     [HttpPost]  
  7. public ActionResult AddAuthor(AuthorBookViewModel model) {  
  8.     Author author = new Author {  
  9.         FirstName = model.FirstName,  
  10.             LastName = model.LastName,  
  11.             Email = model.Email,  
  12.             AddedDate = DateTime.UtcNow,  
  13.             IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString(),  
  14.             ModifiedDate = DateTime.UtcNow,  
  15.             Books = new List < Book > {  
  16.                 new Book {  
  17.                     Name = model.BookName,  
  18.                         ISBN = model.ISBN,  
  19.                         Publisher = model.Publisher,  
  20.                         IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString(),  
  21.                         AddedDate = DateTime.UtcNow,  
  22.                         ModifiedDate = DateTime.UtcNow  
  23.                 }  
  24.             }  
  25.     };  
  26.     repoAuthor.Insert(author);  
  27.     return RedirectToAction("Index");  
  28. }  
The GET request for the AddAuthor action method returns _AddAuthor partial view,  which code snippet is following under the Author folder of views.
  1. @model AuthorBookViewModel  
  2. @using GR.Web.Models < form asp - action = "AddAuthor"  
  3. role = "form" > @await Html.PartialAsync("_ModalHeader"new ModalHeader {  
  4.         Heading = "Add Author"  
  5.     }) < div class = "modal-body form-horizontal" > < div class = "row" > < div class = "col-lg-6" > < div class = "form-group" > < label asp -  
  6.     for = "FirstName"  
  7. class = "col-lg-3 col-sm-3 control-label" > < /label> < div class = "col-lg-6" > < input asp -  
  8.     for = "FirstName"  
  9. class = "form-control" / > < /div> < /div> < div class = "form-group" > < label asp -  
  10.     for = "LastName"  
  11. class = "col-lg-3 col-sm-3 control-label" > < /label> < div class = "col-lg-6" > < input asp -  
  12.     for = "LastName"  
  13. class = "form-control" / > < /div> < /div> < div class = "form-group" > < label asp -  
  14.     for = "Email"  
  15. class = "col-lg-3 col-sm-3 control-label" > < /label> < div class = "col-lg-6" > < input asp -  
  16.     for = "Email"  
  17. class = "form-control" / > < /div> < /div> < /div> < div class = "col-lg-6" > < div class = "form-group" > < label asp -  
  18.     for = "BookName"  
  19. class = "col-lg-3 col-sm-3 control-label" > < /label> < div class = "col-lg-6" > < input asp -  
  20.     for = "BookName"  
  21. class = "form-control" / > < /div> < /div> < div class = "form-group" > < label asp -  
  22.     for = "ISBN"  
  23. class = "col-lg-3 col-sm-3 control-label" > < /label> < div class = "col-lg-6" > < input asp -  
  24.     for = "ISBN"  
  25. class = "form-control" / > < /div> < /div> < div class = "form-group" > < label asp -  
  26.     for = "Publisher"  
  27. class = "col-lg-3 col-sm-3 control-label" > < /label> < div class = "col-lg-6" > < input asp -  
  28.     for = "Publisher"  
  29. class = "form-control" / > < /div> < /div> < /div> < /div> < /div>  
  30. @await Html.PartialAsync("_ModalFooter"new ModalFooter {}) < /form>  
When the Application runs and clicks on the Add Author button, it makes a GET request for the AddAuthor() action, add an author screen, as shown in Figure 3.

enties
Add Author and Book Screen

Edit Author

To pass the data from UI to controller to edit an author, define view model named AuthorViewModel, as per the code snippet, mentioned below.
  1. using System.ComponentModel.DataAnnotations;  
  2. namespace GR.Web.Models {  
  3.     public class AuthorViewModel {  
  4.         [Display(Name = "First Name")]  
  5.         public string FirstName {  
  6.             get;  
  7.             set;  
  8.         }  
  9.         [Display(Name = "Last Name")]  
  10.         public string LastName {  
  11.             get;  
  12.             set;  
  13.         }  
  14.         public string Email {  
  15.             get;  
  16.             set;  
  17.         }  
  18.     }  
  19. }  
The AuthorController has an action method named EditAuthor, which returns view to edit an author. The code snippet is mentioned below for same action method for both GET and Post requests.
  1. [HttpGet]  
  2. public IActionResult EditAuthor(long id) {  
  3.         AuthorViewModel model = new AuthorViewModel();  
  4.         Author author = repoAuthor.Get(id);  
  5.         if (author != null) {  
  6.             model.FirstName = author.FirstName;  
  7.             model.LastName = author.LastName;  
  8.             model.Email = author.Email;  
  9.         }  
  10.         return PartialView("_EditAuthor", model);  
  11.     }  
  12.     [HttpPost]  
  13. public IActionResult EditAuthor(long id, AuthorViewModel model) {  
  14.     Author author = repoAuthor.Get(id);  
  15.     if (author != null) {  
  16.         author.FirstName = model.FirstName;  
  17.         author.LastName = model.LastName;  
  18.         author.Email = model.Email;  
  19.         author.IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();  
  20.         author.ModifiedDate = DateTime.UtcNow;  
  21.         repoAuthor.Update(author);  
  22.     }  
  23.     return RedirectToAction("Index");  
  24. }  
GET request for the EditAuthor action method returns _EditAuthor partial view, where code snippet is following under the Author folder of views.
  1. @model AuthorViewModel  
  2. @using GR.Web.Models < form asp - action = "EditAuthor"  
  3. role = "form" > @await Html.PartialAsync("_ModalHeader"new ModalHeader {  
  4.         Heading = "Edit Author"  
  5.     }) < div class = "modal-body form-horizontal" > < div class = "form-group" > < label asp -  
  6.     for = "FirstName"  
  7. class = "col-lg-3 col-sm-3 control-label" > < /label> < div class = "col-lg-6" > < input asp -  
  8.     for = "FirstName"  
  9. class = "form-control" / > < /div> < /div> < div class = "form-group" > < label asp -  
  10.     for = "LastName"  
  11. class = "col-lg-3 col-sm-3 control-label" > < /label> < div class = "col-lg-6" > < input asp -  
  12.     for = "LastName"  
  13. class = "form-control" / > < /div> < /div> < div class = "form-group" > < label asp -  
  14.     for = "Email"  
  15. class = "col-lg-3 col-sm-3 control-label" > < /label> < div class = "col-lg-6" > < input asp -  
  16.     for = "Email"  
  17. class = "form-control" / > < /div> < /div> < /div>  
  18. @await Html.PartialAsync("_ModalFooter"new ModalFooter {}) < /form>  
When an Application runs and clicks on the Edit button in the Author listing, it makes a GET request for the EditAuthor() action, then the edit author screen is shown in Figure 4.

enties
Edit Author

Add Book

To pass the data from UI to controller to add a book, define view model named BookViewModel, as per the code snippet, mentioned below.
  1. using System.ComponentModel.DataAnnotations;  
  2. namespace GR.Web.Models {  
  3.     public class BookViewModel {  
  4.         [Display(Name = "Book Name")]  
  5.         public string BookName {  
  6.             get;  
  7.             set;  
  8.         }  
  9.         public string ISBN {  
  10.             get;  
  11.             set;  
  12.         }  
  13.         public string Publisher {  
  14.             get;  
  15.             set;  
  16.         }  
  17.     }  
  18. }  
The AuthorController has an action method named AddBook, which returns a view to add a book. The code snippet is mentioned below for same action method for both GET and Post requests.
  1. [HttpGet]  
  2. public PartialViewResult AddBook(long id) {  
  3.         BookViewModel model = new BookViewModel();  
  4.         return PartialView("_AddBook", model);  
  5.     }  
  6.     [HttpPost]  
  7. public IActionResult AddBook(long id, BookViewModel model) {  
  8.     Book book = new Book {  
  9.         AuthorId = id,  
  10.             Name = model.BookName,  
  11.             ISBN = model.ISBN,  
  12.             Publisher = model.Publisher,  
  13.             IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString(),  
  14.             AddedDate = DateTime.UtcNow,  
  15.             ModifiedDate = DateTime.UtcNow  
  16.     };  
  17.     repoBook.Insert(book);  
  18.     return RedirectToAction("Index");  
  19. }  
GET request for the AddBook action method returns _AddBook partial view, where the code snippet is following under the Author folder of the views.
  1. @model BookViewModel  
  2. @using GR.Web.Models < form asp - action = "AddBook"  
  3. role = "form" > @await Html.PartialAsync("_ModalHeader"new ModalHeader {  
  4.         Heading = "Add Book"  
  5.     }) < div class = "modal-body form-horizontal" > < div class = "form-group" > < label asp -  
  6.     for = "BookName"  
  7. class = "col-lg-3 col-sm-3 control-label" > < /label> < div class = "col-lg-6" > < input asp -  
  8.     for = "BookName"  
  9. class = "form-control" / > < /div> < /div> < div class = "form-group" > < label asp -  
  10.     for = "ISBN"  
  11. class = "col-lg-3 col-sm-3 control-label" > < /label> < div class = "col-lg-6" > < input asp -  
  12.     for = "ISBN"  
  13. class = "form-control" / > < /div> < /div> < div class = "form-group" > < label asp -  
  14.     for = "Publisher"  
  15. class = "col-lg-3 col-sm-3 control-label" > < /label> < div class = "col-lg-6" > < input asp -  
  16.     for = "Publisher"  
  17. class = "form-control" / > < /div> < /div> < /div>   
  18. @await Html.PartialAsync("_ModalFooter"new ModalFooter {}) < /form>  
When an Application runs and clicks on the Book button in the Author listing, it makes a GET request for the AddBook() action, then the add book screen is shows below in Figure 5.

enties
Add Book

These operations are about the author controller. As another controller BookController has some more operations such as Book listing, Edit Book and Delete book. The BookController’s constructor injects repository for both Author and Book entities. The code snippet is mentioned below for the same in the BookController.
  1. sing System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using Microsoft.AspNetCore.Mvc;  
  5. using GR.Data;  
  6. using GR.Web.Models;  
  7. using Microsoft.AspNetCore.Mvc.Rendering;  
  8. using Microsoft.AspNetCore.Http;  
  9. namespace GR.Web.Controllers {  
  10.     public class BookController: Controller {  
  11.         private IRepository < Author > repoAuthor;  
  12.         private IRepository < Book > repoBook;  
  13.         public BookController(IRepository < Author > repoAuthor, IRepository < Book > repoBook) {  
  14.             this.repoAuthor = repoAuthor;  
  15.             this.repoBook = repoBook;  
  16.         }  
  17.     }  
  18. }  
Now, click on top menu of the book. It shows the book listing, as shown in Figure 6. The book data is displayed in a tabular format and on this view. These book listing has options to edit a book and delete a book. To pass the data from controller to view, create named BookListingViewModel view model, as shown below. 
  1. namespace GR.Web.Models {  
  2.     public class BookListingViewModel {  
  3.         public long Id {  
  4.             get;  
  5.             set;  
  6.         }  
  7.         public string BookName {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public string AuthorName {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public string ISBN {  
  16.             get;  
  17.             set;  
  18.         }  
  19.         public string Publisher {  
  20.             get;  
  21.             set;  
  22.         }  
  23.     }  
  24. }  
Now, we create an action method, which returns an index view with the data. The code snippet, mentioned below is of Index action method in BookController.
  1. public IActionResult Index() {  
  2.     List < BookListingViewModel > model = new List < BookListingViewModel > ();  
  3.     repoBook.GetAll().ToList().ForEach(b => {  
  4.         BookListingViewModel book = new BookListingViewModel {  
  5.             Id = b.Id,  
  6.                 BookName = b.Name,  
  7.                 Publisher = b.Publisher,  
  8.                 ISBN = b.ISBN  
  9.         };  
  10.         Author author = repoAuthor.Get(b.AuthorId);  
  11.         book.AuthorName = $ "{author.FirstName} {author.LastName}";  
  12.         model.Add(book);  
  13.     });  
  14.     return View("Index", model);  
  15. }  
Now, we create an index view, as per the code snippet, mentioned below under the Book folder of Views.
  1. @model IEnumerable < BookListingViewModel > @using GR.Web.Models  
  2. @using GR.Web.Code < div class = "top-buffer" > < /div> < div class = "panel panel-primary" > < div class = "panel-heading panel-head" > Books < /div> < div class = "panel-body" > < div class = "top-buffer" > < /div> < table class = "table table-bordered table-striped table-condensed" > < thead > < tr > < th > Name < /th> < th > Author Name < /th> < th > ISBN < /th> < th > Publisher < /th> < th > Action < /th> < /tr> < /thead> < tbody > @foreach(var item in Model) { < tr > < td > @Html.DisplayFor(modelItem => item.BookName) < /td> < td > @Html.DisplayFor(modelItem => item.AuthorName) < /td> < td > @Html.DisplayFor(modelItem => item.ISBN) < /td> < td > @Html.DisplayFor(modelItem => item.Publisher) < /td> < td > < a id = "editBookModal"  
  3.     data - toggle = "modal"  
  4.     asp - action = "EditBook"  
  5.     asp - route - id = "@item.Id"  
  6.     data - target = "#modal-action-book"  
  7.     class = "btn btn-info" > < i class = "glyphicon glyphicon-pencil" > < /i> Edit < /a>  < a id = "deleteBookModal"  
  8.     data - toggle = "modal"  
  9.     asp - action = "DeleteBook"  
  10.     asp - route - id = "@item.Id"  
  11.     data - target = "#modal-action-book"  
  12.     class = "btn btn-danger" > < i class = "glyphicon glyphicon-trash" > < /i> Delete < /a>  < /td> < /tr>  
  13. } < /tbody> < /table> < /div> < /div>  
  14. @Html.Partial("_Modal"new BootstrapModel {  
  15.     ID = "modal-action-book", AreaLabeledId = "modal-action-book-label", Size = ModalSize.Medium  
  16. })  
  17. @section scripts { < script src = "~/js/book-index.js"  
  18.     asp - append - version = "true" > < /script>  
  19. }  
It shows all forms in bootstrap model popup, so create the book-index.js file, as per the code snippet, mentioned below.
  1. (function($) {  
  2.     function Book() {  
  3.         var $this = this;  
  4.   
  5.         function initilizeModel() {  
  6.             $("#modal-action-book").on('loaded.bs.modal'function(e) {}).on('hidden.bs.modal'function(e) {  
  7.                 $(this).removeData('bs.modal');  
  8.             });  
  9.         }  
  10.         $this.init = function() {  
  11.             initilizeModel();  
  12.         }  
  13.     }  
  14.     $(function() {  
  15.         var self = new Book();  
  16.         self.init();  
  17.     })  
  18. }(jQuery))  
When we run the Application and click on top menu Book, which calls index() action method with a HttpGet request from BookController, then we get all the book listed in the UI, as shown below.

enties
Book Listing

Edit Book

To pass the data from UI to controller to edit a book, define view model named EditBookViewModel, as shown below.
  1. using Microsoft.AspNetCore.Mvc.Rendering;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. namespace GR.Web.Models {  
  5.     public class EditBookViewModel {  
  6.         [Display(Name = "Book Name")]  
  7.         public string BookName {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public string ISBN {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public string Publisher {  
  16.             get;  
  17.             set;  
  18.         }  
  19.         public List < SelectListItem > Authors {  
  20.             get;  
  21.             set;  
  22.         } = new List < SelectListItem > ();  
  23.         [Display(Name = "Author")]  
  24.         public long AuthorId {  
  25.             get;  
  26.             set;  
  27.         }  
  28.     }  
  29. }  
The BookController has an action method named EditBook, which returns view for editing a book. The code snippet is mentioned below for same action method for both GET and Post requests.
  1. public PartialViewResult EditBook(long id) {  
  2.         EditBookViewModel model = new EditBookViewModel();  
  3.         model.Authors = repoAuthor.GetAll().Select(a => new SelectListItem {  
  4.             Text = $ "{a.FirstName} {a.LastName}",  
  5.                 Value = a.Id.ToString()  
  6.         }).ToList();  
  7.         Book book = repoBook.Get(id);  
  8.         if (book != null) {  
  9.             model.BookName = book.Name;  
  10.             model.ISBN = book.ISBN;  
  11.             model.Publisher = book.Publisher;  
  12.             model.AuthorId = book.AuthorId;  
  13.         }  
  14.         return PartialView("_EditBook", model);  
  15.     }  
  16.     [HttpPost]  
  17. public ActionResult EditBook(long id, EditBookViewModel model) {  
  18.     Book book = repoBook.Get(id);  
  19.     if (book != null) {  
  20.         book.Name = model.BookName;  
  21.         book.ISBN = model.ISBN;  
  22.         book.Publisher = model.Publisher;  
  23.         book.AuthorId = model.AuthorId;  
  24.         book.IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();  
  25.         book.ModifiedDate = DateTime.UtcNow;  
  26.         repoBook.Update(book);  
  27.     }  
  28.     return RedirectToAction("Index");  
  29. }  
The GET request for the EditBook action method returns _EditBook partial view, where code snippet is mentioned below under the Book folder of views.
  1. @model EditBookViewModel  
  2. @using GR.Web.Models < form asp - action = "EditBook"  
  3. role = "form" > @await Html.PartialAsync("_ModalHeader"new ModalHeader {  
  4.         Heading = "Edit Book"  
  5.     }) < div class = "modal-body form-horizontal" > < div class = "form-group" > < label asp -  
  6.     for = "BookName"  
  7. class = "col-lg-3 col-sm-3 control-label" > < /label> < div class = "col-lg-6" > < input asp -  
  8.     for = "BookName"  
  9. class = "form-control" / > < /div> < /div> < div class = "form-group" > < label asp -  
  10.     for = "ISBN"  
  11. class = "col-lg-3 col-sm-3 control-label" > < /label> < div class = "col-lg-6" > < input asp -  
  12.     for = "ISBN"  
  13. class = "form-control" / > < /div> < /div> < div class = "form-group" > < label asp -  
  14.     for = "Publisher"  
  15. class = "col-lg-3 col-sm-3 control-label" > < /label> < div class = "col-lg-6" > < input asp -  
  16.     for = "Publisher"  
  17. class = "form-control" / > < /div> < /div> < div class = "form-group" > < label asp -  
  18.     for = "AuthorId"  
  19. class = "col-lg-3 col-sm-3 control-label" > < /label> < div class = "col-lg-6" > < select asp -  
  20.     for = "AuthorId"  
  21. asp - items = "@Model.Authors"  
  22. class = "form-control" > < option > Please select < /option> < /select>  < /div> < /div> < /div>  
  23. @await Html.PartialAsync("_ModalFooter"new ModalFooter {}) < /form>  
When an Application runs and clicks the Edit button in the listed books, it makes a GET request for the EditBook() action, then the edit book screen is shown below.

enties
Edit Book

Delete Book

The BookController has an action method named DeleteBook, which returns view to delete a book. The code snippet is mentioned below for same action method for both GET and Post requests.
  1. [HttpGet]  
  2. public PartialViewResult DeleteBook(long id) {  
  3.         Book book = repoBook.Get(id);  
  4.         return PartialView("_DeleteBook", book ? .Name);  
  5.     }  
  6.     [HttpPost]  
  7. public ActionResult DeleteBook(long id, FormCollection form) {  
  8.     Book book = repoBook.Get(id);  
  9.     if (book != null) {  
  10.         repoBook.Delete(book);  
  11.     }  
  12.     return RedirectToAction("Index");  
  13. }  
  14. The GET request  
  15. for the DeleteBook action method returns _DeleteBook partial view which code snippet is following under the Book folder of Views.  
  16. @model string  
  17. @using GR.Web.Models < form asp - action = "DeleteBook"  
  18. role = "form" > @Html.Partial("_ModalHeader"new ModalHeader {  
  19.     Heading = "Delete Book"  
  20. }) < div class = "modal-body form-horizontal" > Are you want to delete @Model ? < /div>  
  21. @Html.Partial("_ModalFooter"new ModalFooter {  
  22.     SubmitButtonText = "Delete"  
  23. }) < /form>  
When an Application runs and you click on the Delete button in the listed books, it makes a GET request for the DeleteBook() action, then the delete book screen is shown below.

enties
Delete Book

Download

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

See Also

Its recommended to read more articles related to ASP.NET Core.

  1. Overview Of ASP.NET Core
  2. ASP.NET Core With Visual Studio 2017 RC
  3. CRUD Operations in ASP.NET Core using Entity Framework Core Code First
  4. Repository Pattern In ASP.NET Core
  5. Generic Repository Pattern In ASP.NET Core

Conclusion

This article introduced the generic 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.

Up Next
    Ebook Download
    View all
    Learn
    View all