CRUD Operations Using the Generic Repository Pattern and Unit of Work in MVC

Introduction

This article introduces the Generic Repository pattern and Unit of Work in ASP.NET MVC applications. We are developing an application for a Book entity on which we can do Create, Read, Update and Delete operations. To keep the article simple and to make it easy to understand the Generic Repository pattern and Unit of Work, we use a single book entity in the application.

In the previous article “CRUD Operations Using the Repository Pattern in MVC” , we created a book repository for a book entity and it's good for one entity that does CRUD operations but suppose we have an enterprise level application and that application has more than one entity so we need to create a repository for each entity. In short we can say that we are repeating the code for each entity's repository against DRY (every piece of knowledge must have a single, unambiguous, authoritative representation within a system) principle in the software engineering; that's why we need a generic repository pattern. As in Figure 1.1, two developers have question “Whether to create a new part or to reuse an existing one.” One developer choose the option to create a new one as discussed in the article CRUD Operations Using the Repository Pattern in MVC but another developer choose the second option, to reuse an existing code so that you can reduce code. So now you are the second developer and your approach is Generic Repository Pattern and Unit of Work and it's also the main goal of this article as well.



Figure 1.1 Reuse and Reduce (Courtesy: http://perspectives.3ds.com/ )

The Repository Pattern

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.

In this article we design a common generic repository for all entities and a Unit of work class. The Unit of Work class creates a repository instance for each entity and the repository is used to do CURD operations. We create an instance of the UnitOfWork class in the controller then create a repository instance depending on the entity and thereafter uses the methods of the repository as per the operations.

The following diagram shows the relationship between the repository and the Entity Framework data context, in which MVC controllers interact with the repository by a Unit of Work rather than directly with the Entity Framework.



Figure 1.2 Generic Repository Pattern and Unit of Work workflow

Why Unit of Work

A Unit of Work, as it's name applies, does something. In this article a Unit of Work does whatever that we create an instance of it then it instantiates our DbContext thereafter each repository instance uses the same DbContext for database operations. So the Unit of Work is the pattern that ensures that all repositories use the same database context.

Implement a Generic Repository and a Unit of Work Class

Note: In this article your user interface uses a concrete class object, not an interface because that concept I will describe in the next article. To keep this short code and only describe the concepts, I removed error handling code from the controller but you should always use error handling in your controller.

In this section of articles we create two projects, one is EF.Core and another is EF.Data. In this article we are working with Entity Framework Code First Approach so the project EF.Core contains entities that are needed in the application's database. In this EF.Data project, we create two entities, one is the BaseEntity class that has common properties that will be inherited by each entity and the other is Book. Let's see each entity. The following is a code snippet for the BaseEntity class.

  1. using System;  
  2.   
  3. namespace EF.Core  
  4. {  
  5.    public abstract class BaseEntity  
  6.     {  
  7.         public Int64 ID { getset; }  
  8.         public DateTime AddedDate { getset; }  
  9.         public DateTime ModifiedDate { getset; }  
  10.         public string IP { getset; }  
  11.     }  

Now we create a Book entity under the Data folder of the EF.Core project which inherits from the BaseEntity class. The following is a code snippet for the Book entity.

  1. using System;  
  2.   
  3. namespace EF.Core.Data  
  4. {  
  5.    public class Book : BaseEntity  
  6.     {  
  7.        public string Title { getset; }  
  8.        public string Author { getset; }  
  9.        public string ISBN { getset; }  
  10.        public DateTime Published { getset; }  
  11.     }  

The EF.Data project contains DataContext, Book entity Mapping, Repository and Unit of Work classes. The ADO.NET Entity Framework Code First data access approach requires us to create a data access context class that inherits from the DbContext class so we create a context class EFDbContext (EFDbContext.cs) class. In this class, we override the OnModelCreating() method. This method is called when the model for a context class (EFDbContext) 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 System;  
  2. using System.Data.Entity;  
  3. using System.Data.Entity.ModelConfiguration;  
  4. using System.Linq;  
  5. using System.Reflection;  
  6. using EF.Core;  
  7.   
  8. namespace EF.Data  
  9. {  
  10.    public class EFDbContext : DbContext  
  11.     {  
  12.        public EFDbContext()  
  13.            : base("name=DbConnectionString")  
  14.        {  
  15.        }  
  16.   
  17.        public new IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity  
  18.        {  
  19.            return base.Set<TEntity>();  
  20.        }  
  21.   
  22.        protected override void OnModelCreating(DbModelBuilder modelBuilder)  
  23.        {  
  24.            var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()  
  25.           .Where(type => !String.IsNullOrEmpty(type.Namespace))  
  26.           .Where(type => type.BaseType != null && type.BaseType.IsGenericType  
  27.                && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));  
  28.            foreach (var type in typesToRegister)  
  29.            {  
  30.                dynamic configurationInstance = Activator.CreateInstance(type);  
  31.                modelBuilder.Configurations.Add(configurationInstance);  
  32.            }  
  33.            base.OnModelCreating(modelBuilder);  
  34.        }  
  35.     }  

As you know, the EF Code First approach follows convention over configuration, so in the constructor, we just pass the connection string name, the same as an App.Config file and it connects to that server. In the OnModelCreating() method, we used reflection to map an entity to its configuration class in this specific project.



Figure 1.3 Project structure in solution

Now, we define the configuration for the book entity that will be used when the database table will be created by the entity. The configuration defines the class library project EF.Data under the Mapping folder. Now create configuration classes for the entity. For the Book entity, we create the BookMap entity.

The following is a code snippet for the BookMap class.

  1. using System.ComponentModel.DataAnnotations.Schema;  
  2. using System.Data.Entity.ModelConfiguration;  
  3. using EF.Core.Data;  
  4.   
  5. namespace EF.Data.Mapping  
  6. {  
  7.    public class  BookMap : EntityTypeConfiguration<Book>  
  8.     {  
  9.        public BookMap()  
  10.        {  
  11.            HasKey(t => t.ID);  
  12.            Property(t => t.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);  
  13.            Property(t => t.Title).IsRequired();  
  14.            Property(t => t.Author).IsRequired();  
  15.            Property(t => t.ISBN).IsRequired();  
  16.            Property(t => t.Published).IsRequired();  
  17.            ToTable("Books");  
  18.        }  
  19.     }  

Now we create a generic repository class. We are not creating an interface for a repository so that our article will be easy to understand. This generic repository has all CURD operation methods. 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 all the repositories for each entity has the same context. We are using the saveChanges() method of the context but you can also use the save method of the Unit of Work class because both have the same context. The following is a code snippet for the Generic Repository.

  1. using System;  
  2. using System.Data.Entity;  
  3. using System.Data.Entity.Validation;  
  4. using System.Linq;  
  5. using EF.Core;  
  6.   
  7. namespace EF.Data  
  8. {  
  9.    public class Repository<T> where T : BaseEntity  
  10.     {  
  11.         private readonly EFDbContext context;  
  12.         private IDbSet<T> entities;  
  13.         string errorMessage = string.Empty;  
  14.   
  15.         public Repository(EFDbContext context)  
  16.         {  
  17.             this.context = context;  
  18.         }  
  19.   
  20.         public T GetById(object id)  
  21.         {  
  22.             return this.Entities.Find(id);  
  23.         }  
  24.   
  25.         public void Insert(T entity)  
  26.         {  
  27.             try  
  28.             {  
  29.                 if (entity == null)  
  30.                 {  
  31.                     throw new ArgumentNullException("entity");  
  32.                 }  
  33.                 this.Entities.Add(entity);  
  34.                 this.context.SaveChanges();  
  35.             }  
  36.             catch (DbEntityValidationException dbEx)  
  37.             {                 
  38.   
  39.                 foreach (var validationErrors in dbEx.EntityValidationErrors)  
  40.                 {  
  41.                     foreach (var validationError in validationErrors.ValidationErrors)  
  42.                     {  
  43.                         errorMessage += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine;  
  44.                     }  
  45.                 }  
  46.                 throw new Exception(errorMessage, dbEx);                
  47.             }  
  48.         }  
  49.   
  50.         public void Update(T entity)  
  51.         {  
  52.             try  
  53.             {  
  54.                 if (entity == null)  
  55.                 {  
  56.                     throw new ArgumentNullException("entity");  
  57.                 }  
  58.                 this.context.SaveChanges();  
  59.             }  
  60.             catch (DbEntityValidationException dbEx)  
  61.             {  
  62.                 foreach (var validationErrors in dbEx.EntityValidationErrors)  
  63.                 {  
  64.                     foreach (var validationError in validationErrors.ValidationErrors)  
  65.                     {  
  66.                         errorMessage += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);  
  67.                     }  
  68.                 }  
  69.   
  70.                 throw new Exception(errorMessage, dbEx);                  
  71.             }  
  72.         }  
  73.   
  74.         public void Delete(T entity)  
  75.         {  
  76.             try  
  77.             {  
  78.                 if (entity == null)  
  79.                 {  
  80.                     throw new ArgumentNullException("entity");  
  81.                 }  
  82.   
  83.                 this.Entities.Remove(entity);  
  84.                 this.context.SaveChanges();  
  85.             }  
  86.             catch (DbEntityValidationException dbEx)  
  87.             {  
  88.   
  89.                 foreach (var validationErrors in dbEx.EntityValidationErrors)  
  90.                 {  
  91.                     foreach (var validationError in validationErrors.ValidationErrors)  
  92.                     {  
  93.                         errorMessage += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);  
  94.                     }  
  95.                 }  
  96.                 throw new Exception(errorMessage, dbEx);                  
  97.             }  
  98.         }  
  99.   
  100.         public virtual IQueryable<T> Table  
  101.         {  
  102.             get  
  103.             {  
  104.                 return this.Entities;  
  105.             }  
  106.         }  
  107.   
  108.         private IDbSet<T> Entities  
  109.         {  
  110.             get  
  111.             {  
  112.                 if (entities == null)  
  113.                 {  
  114.                     entities = context.Set<T>();  
  115.                 }  
  116.                 return entities;  
  117.             }  
  118.         }  
  119.     }  

Now to create a class for the Unit of Work; that class is UnitOfWork. This class inherits from an IDisposable interface so that its instance will be disposed of in each controller. This class initiates the application DataContext. This class heart is the Repository<T>() method that returns a repository for the entity and that entity inherits from the BaseEntity class. The following is a code snippet for the UnitOfWork class.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using EF.Core;  
  4.   
  5. namespace EF.Data  
  6. {  
  7.    public class UnitOfWork : IDisposable  
  8.     {  
  9.        private readonly EFDbContext context;  
  10.        private bool disposed;  
  11.        private Dictionary<string,object> repositories;  
  12.   
  13.        public UnitOfWork(EFDbContext context)  
  14.        {  
  15.            this.context = context;  
  16.        }  
  17.   
  18.        public UnitOfWork()  
  19.        {  
  20.            context = new EFDbContext();  
  21.        }  
  22.   
  23.        public void Dispose()  
  24.        {  
  25.            Dispose(true);  
  26.            GC.SuppressFinalize(this);  
  27.        }  
  28.   
  29.        public void Save()  
  30.        {  
  31.            context.SaveChanges();  
  32.        }  
  33.   
  34.        public virtual void Dispose(bool disposing)  
  35.        {  
  36.            if (!disposed)  
  37.            {  
  38.                if (disposing)  
  39.                {  
  40.                    context.Dispose();  
  41.                }  
  42.            }  
  43.            disposed = true;  
  44.        }  
  45.   
  46.        public Repository<T> Repository<T>() where T : BaseEntity  
  47.        {  
  48.            if (repositories == null)  
  49.            {  
  50.                repositories = new Dictionary<string,object>();  
  51.            }  
  52.   
  53.            var type = typeof(T).Name;  
  54.   
  55.            if (!repositories.ContainsKey(type))  
  56.            {  
  57.                var repositoryType = typeof(Repository<>);  
  58.                var repositoryInstance = Activator.CreateInstance(repositoryType.MakeGenericType(typeof(T)), context);  
  59.                repositories.Add(type, repositoryInstance);  
  60.            }  
  61.            return (Repository<T>)repositories[type];  
  62.        }  
  63.     }  

An MVC Application Using the Generic Repository Pattern

Now we create a MVC application (EF.Web) as in Figure 1.3. This is our third project of the application, this project contains user interface for a Book entity's CURD operations and the controller to do these operations. First we proceed to the controller. Create a BookController 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 Unit of Work class instance then the controller's constructor initiates the repository as per the required entity. The following is a code snippet for the BookController.

  1. using System.Collections.Generic;  
  2. using System.Linq;  
  3. using System.Web.Mvc;  
  4. using EF.Core.Data;  
  5. using EF.Data;  
  6.   
  7. namespace EF.Web.Controllers  
  8. {  
  9.     public class BookController : Controller  
  10.     {  
  11.         private UnitOfWork unitOfWork = new UnitOfWork();  
  12.         private Repository<Book> bookRepository;  
  13.   
  14.         public BookController()  
  15.         {  
  16.             bookRepository = unitOfWork.Repository<Book>();  
  17.         }  
  18.   
  19.         public ActionResult Index()  
  20.         {  
  21.             IEnumerable<Book> books = bookRepository.Table.ToList();  
  22.             return View(books);  
  23.         }  
  24.   
  25.         public ActionResult CreateEditBook(int? id)  
  26.         {  
  27.             Book model = new Book();  
  28.             if (id.HasValue)  
  29.             {  
  30.                 model = bookRepository.GetById(id.Value);  
  31.             }  
  32.             return View(model);  
  33.         }  
  34.   
  35.         [HttpPost]  
  36.         public ActionResult CreateEditBook(Book model)  
  37.         {  
  38.             if (model.ID == 0)  
  39.             {  
  40.                 model.ModifiedDate = System.DateTime.Now;  
  41.                 model.AddedDate = System.DateTime.Now;  
  42.                 model.IP = Request.UserHostAddress;  
  43.                 bookRepository.Insert(model);  
  44.             }  
  45.             else  
  46.             {  
  47.                 var editModel = bookRepository.GetById(model.ID);  
  48.                 editModel.Title = model.Title;  
  49.                 editModel.Author = model.Author;  
  50.                 editModel.ISBN = model.ISBN;  
  51.                 editModel.Published = model.Published;  
  52.                 editModel.ModifiedDate = System.DateTime.Now;  
  53.                 editModel.IP = Request.UserHostAddress;  
  54.                 bookRepository.Update(editModel);  
  55.             }  
  56.   
  57.             if (model.ID > 0)  
  58.             {  
  59.                 return RedirectToAction("Index");  
  60.             }  
  61.             return View(model);  
  62.         }  
  63.   
  64.         public ActionResult DeleteBook(int id)  
  65.         {  
  66.             Book model = bookRepository.GetById(id);  
  67.             return View(model);  
  68.         }  
  69.   
  70.         [HttpPost,ActionName("DeleteBook")]  
  71.         public ActionResult ConfirmDeleteBook(int id)  
  72.         {  
  73.             Book model = bookRepository.GetById(id);  
  74.             bookRepository.Delete(model);  
  75.             return RedirectToAction("Index");  
  76.         }  
  77.   
  78.         public ActionResult DetailBook(int id)  
  79.         {  
  80.             Book model = bookRepository.GetById(id);  
  81.             return View(model);  
  82.         }  
  83.   
  84.         protected override void Dispose(bool disposing)  
  85.         {  
  86.             unitOfWork.Dispose();  
  87.             base.Dispose(disposing);  
  88.         }  
  89.     }  

We have now developed the BookController to handle CURD operation request for a book entity. Now to develop the user interface for the CRUD operations. We develop it for the views for adding and editing a book, a book listing, book delete and book details. Let's see each one by one.

Create / Edit Book View

We create a common view for creating and editing a book such as CreateEditBook.cshtml under the Book folder of the views. We use a date picker to choose the date for the book published date. That is why we write JavaScript code for date picker.

  1. (function ($) {  
  2.     function Book() {  
  3.         var $thisthis = this;  
  4.         function initializeAddEditBook() {  
  5.             $('.datepicker').datepicker({  
  6.                 "setDate": new Date(),  
  7.                 "autoclose": true  
  8.             });              
  9.         }  
  10.         $this.init = function () {              
  11.             initializeAddEditBook();  
  12.         }  
  13.     }  
  14.     $(function () {  
  15.         var self = new Book();  
  16.         self.init();  
  17.     });  
  18. }(jQuery)) 

Now define a create/edit book view and the following is a code snippet for CreateEditBook.cshtml.

  1. @model EF.Core.Data.Book  
  2.   
  3. @{  
  4.     ViewBag.Title = "Create Edit Book";  
  5. }  
  6. <div class="book-example panel panel-primary">  
  7.     <div class="panel-heading panel-head">Add / Edit Book</div>  
  8.     <div class="panel-body">  
  9.         @using (Html.BeginForm())  
  10.         {         
  11.             <div class="form-horizontal">  
  12.                 <div class="form-group">  
  13.                     @Html.LabelFor(model => model.Title, new { @class = "col-lg-1 control-label" })  
  14.                     <div class="col-lg-9">  
  15.                         @Html.TextBoxFor(model => model.Title, new { @class = "form-control" })  
  16.                     </div>  
  17.                 </div>  
  18.                 <div class="form-group">  
  19.                     @Html.LabelFor(model => model.ISBN, new { @class = "col-lg-1 control-label" })  
  20.                     <div class="col-lg-9">  
  21.                         @Html.TextBoxFor(model => model.ISBN, new { @class = "form-control" })  
  22.                     </div>  
  23.                 </div>  
  24.                 <div class="form-group">  
  25.                     @Html.LabelFor(model => model.Author, new { @class = "col-lg-1 control-label" })  
  26.                     <div class="col-lg-9">  
  27.                         @Html.TextBoxFor(model => model.Author, new { @class = "form-control" })  
  28.                     </div>  
  29.                 </div>  
  30.                 <div class="form-group">  
  31.                     @Html.LabelFor(model => model.Published, new { @class = "col-lg-1 control-label" })  
  32.                     <div class="col-lg-9">  
  33.                         @Html.TextBoxFor(model => model.Published, new { @class = "form-control datepicker" })  
  34.                     </div>  
  35.                 </div>  
  36.                 <div class="form-group">  
  37.                     <div class="col-lg-8"></div>  
  38.                     <div class="col-lg-3">  
  39.                         @Html.ActionLink("Back to List", "Index", null, new { @class = "btn btn-default" })  
  40.                         <button class="btn btn-success" id="btnSubmit" type="submit">  
  41.                             Submit  
  42.                         </button>  
  43.                     </div>  
  44.                 </div>  
  45.             </div>         
  46.         }  
  47.     </div>  
  48. </div>  
  49. @section scripts  
  50. {  
  51.     <script src="~/Scripts/bootstrap-datepicker.js" type="text/javascript"></script>  
  52.     <script src="~/Scripts/book-create-edit.js" type="text/javascript"></script>  

Now run the application and call the CreateEditBook() action method with a HttpGet request, then we get the UI as in Figure 1.4 to add a new book to the application.



Figure 1.4 : Add new book UI

When we click on the submit button then the CreateEditBook() action method is called with a HttpPost request and the new data is saved to the database.

Book List View

This is the first view when the application is accessed or the entry point of the application is executed. It shows the book listing as in Figure 1.5. We display book data in tabular format and on this view we create links to add a new book, edit a book, delete a book and the details of a book. This view is an index view and the following is a code snippet for index.cshtml under the Book folder of View.

  1. @model IEnumerable<EF.Core.Data.Book>  
  2. @using EF.Web.Models  
  3.   
  4. <div class="book-example panel panel-primary">  
  5.     <div class="panel-heading panel-head">Books Listing</div>  
  6.     <div class="panel-body">  
  7.         <a id="createEditBookModal" href="@Url.Action("CreateEditBook")" class="btn btn-success">  
  8.             <span class="glyphicon glyphicon-plus"></span>Book  
  9.         </a>  
  10.   
  11.         <table class="table" style="margin: 4px">  
  12.             <tr>  
  13.                 <th>  
  14.                     @Html.DisplayNameFor(model => model.Title)  
  15.                 </th>  
  16.                 <th>  
  17.                     @Html.DisplayNameFor(model => model.Author)  
  18.                 </th>  
  19.                 <th>  
  20.                     @Html.DisplayNameFor(model => model.ISBN)  
  21.                 </th>  
  22.                 <th>Action  
  23.                 </th>  
  24.   
  25.                 <th></th>  
  26.             </tr>  
  27.             @foreach (var item in Model)  
  28.             {  
  29.                 <tr>  
  30.                     <td>  
  31.                         @Html.DisplayFor(modelItem => item.Title)  
  32.                     </td>  
  33.                     <td>  
  34.                         @Html.DisplayFor(modelItem => item.Author)  
  35.                     </td>  
  36.                     <td>  
  37.                         @Html.DisplayFor(modelItem => item.ISBN)  
  38.                     </td>  
  39.                     <td>  
  40.                         @Html.ActionLink("Edit", "CreateEditBook", new { id = item.ID }, new { @class = "btn btn-success" }) |  
  41.                         @Html.ActionLink("Details", "DetailBook", new { id = item.ID }, new { @class = "btn btn-primary" }) |  
  42.                         @Html.ActionLink("Delete", "DeleteBook", new { id = item.ID }, new { @class = "btn btn-danger" })  
  43.                     </td>  
  44.                 </tr>  
  45.             }  
  46.   
  47.         </table>  
  48.     </div>  
  49. </div> 

When we run the application and call the index() action with a HttpGet request then we get all the books listed in the UI as in Figure 1.5. This UI has options for CRUD operations.



Figure 1.5 Books Listing UI.

As in the figure above each book has an option for Edit; when we click on the Edit button then the CreateEditBook() action method is called with a HttpGet request and the UI is shown as in Figure 1.6.



Figure 1.6 Edit a book UI.

Now we change input field data and click on the submit button then the CreateEditBook() action method is called with a HttpPost request and that book data is successfully updated in the database.
Book Detail View

We create a view that shows specific book details when the details button is clicked in the book listing data. We call the DetailBook() action method with a HttpGet request that shows a “Details” view such as in Figure 1.7 so we create a view DetailBook and the following is a code snippet for DetailBook.cshtml.

  1. @model EF.Core.Data.Book  
  2. @{  
  3.     ViewBag.Title = "Detail Book";  
  4. }  
  5. <div class="book-example panel panel-primary">  
  6.     <div class="panel-heading panel-head">Book Detail</div>  
  7.     <div class="panel-body">  
  8.         <div class="form-horizontal">  
  9.             <div class="form-group">  
  10.                 @Html.LabelFor(model => model.Title, new { @class = "col-lg-1 control-label" })  
  11.                 <div class="col-lg-9">  
  12.                     @Html.DisplayFor(model => model.Title, new { @class = "form-control" })  
  13.                 </div>  
  14.             </div>  
  15.   
  16.             <div class="form-group">  
  17.                 @Html.LabelFor(model => model.Author, new { @class = "col-lg-1 control-label" })  
  18.                 <div class="col-lg-9">  
  19.                     @Html.DisplayFor(model => model.Author, new { @class = "form-control" })  
  20.                 </div>  
  21.             </div>  
  22.   
  23.             <div class="form-group">  
  24.                 @Html.LabelFor(model => model.ISBN, new { @class = "col-lg-1 control-label" })  
  25.                 <div class="col-lg-9">  
  26.                     @Html.DisplayFor(model => model.ISBN, new { @class = "form-control" })  
  27.                 </div>  
  28.             </div>  
  29.   
  30.             <div class="form-group">  
  31.                 @Html.LabelFor(model => model.Published, new { @class = "col-lg-1 control-label" })  
  32.                 <div class="col-lg-9">  
  33.                     @Html.DisplayFor(model => model.Published, new { @class = "form-control" })  
  34.                 </div>  
  35.             </div>  
  36.   
  37.             <div class="form-group">  
  38.                 @Html.LabelFor(model => model.AddedDate, new { @class = "col-lg-1 control-label" })  
  39.                 <div class="col-lg-9">  
  40.                     @Html.DisplayFor(model => model.AddedDate, new { @class = "form-control" })  
  41.                 </div>  
  42.             </div>  
  43.   
  44.             <div class="form-group">  
  45.                 @Html.LabelFor(model => model.ModifiedDate, new { @class = "col-lg-1 control-label" })  
  46.                 <div class="col-lg-9">  
  47.                     @Html.DisplayFor(model => model.ModifiedDate, new { @class = "form-control" })  
  48.                 </div>  
  49.             </div>  
  50.   
  51.             <div class="form-group">  
  52.                 @Html.LabelFor(model => model.IP, new { @class = "col-lg-1 control-label" })  
  53.                 <div class="col-lg-9">  
  54.                     @Html.DisplayFor(model => model.IP, new { @class = "form-control" })  
  55.                 </div>  
  56.             </div>  
  57.   
  58.             @using (Html.BeginForm())  
  59.             {  
  60.                 <div class="form-group">  
  61.                     <div class="col-lg-1"></div>  
  62.                     <div class="col-lg-9">  
  63.                         @Html.ActionLink("Edit", "CreateEditBook", new { id = Model.ID }, new { @class = "btn btn-primary" })  
  64.                         @Html.ActionLink("Back to List", "Index", null, new { @class = "btn btn-success" })  
  65.                     </div>  
  66.                 </div>  
  67.             }  
  68.         </div>  
  69.     </div>  
  70. </div> 




Figure 1.7 Book Detail UI

Delete Book

Delete a book is the last operation of this article. To delete a book we follow the process of clicking on the Delete button that exists in the Book listing data then the book detail view shows to ask “You are sure you want to delete this?” after clicking on the Delete button that exists in the Delete view such as in Figure 1.8. When we click the Delete button of the book list then it makes a HttpGet request that calls the DeleteBook() action method that shows a delete view then clicks on the Delete button of the view then an HttpPost request makes that call to ConfirmDeleteBook() action methods that delete that book.

The following is a code snippet for DeleteBook.cshtml.

  1. @model EF.Core.Data.Book  
  2.   
  3. @{  
  4.     ViewBag.Title = "Delete Book";  
  5. }  
  6.   
  7. <div class="book-example panel panel-primary">  
  8.     <div class="panel-heading panel-head">Delete Book</div>  
  9.     <div class="panel-body">  
  10.         <h3>Are you sure you want to delete this?</h3>  
  11.         <h1>@ViewBag.ErrorMessage</h1>  
  12.         <div class="form-horizontal">  
  13.             <div class="form-group">  
  14.                 @Html.LabelFor(model => model.Title, new { @class = "col-lg-1 control-label" })  
  15.                 <div class="col-lg-9">  
  16.                     @Html.DisplayFor(model => model.Title, new { @class = "form-control" })  
  17.                 </div>  
  18.             </div>  
  19.   
  20.             <div class="form-group">  
  21.                 @Html.LabelFor(model => model.Author, new { @class = "col-lg-1 control-label" })  
  22.                 <div class="col-lg-9">  
  23.                     @Html.DisplayFor(model => model.Author, new { @class = "form-control" })  
  24.                 </div>  
  25.             </div>  
  26.   
  27.             <div class="form-group">  
  28.                 @Html.LabelFor(model => model.ISBN, new { @class = "col-lg-1 control-label" })  
  29.                 <div class="col-lg-9">  
  30.                     @Html.DisplayFor(model => model.ISBN, new { @class = "form-control" })  
  31.                 </div>  
  32.             </div>  
  33.   
  34.             <div class="form-group">  
  35.                 @Html.LabelFor(model => model.Published, new { @class = "col-lg-1 control-label" })  
  36.                 <div class="col-lg-9">  
  37.                     @Html.DisplayFor(model => model.Published, new { @class = "form-control" })  
  38.                 </div>  
  39.             </div>  
  40.   
  41.             <div class="form-group">  
  42.                 @Html.LabelFor(model => model.AddedDate, new { @class = "col-lg-1 control-label" })  
  43.                 <div class="col-lg-9">  
  44.                     @Html.DisplayFor(model => model.AddedDate, new { @class = "form-control" })  
  45.                 </div>  
  46.             </div>  
  47.   
  48.             <div class="form-group">  
  49.                 @Html.LabelFor(model => model.ModifiedDate, new { @class = "col-lg-1 control-label" })  
  50.                 <div class="col-lg-9">  
  51.                     @Html.DisplayFor(model => model.ModifiedDate, new { @class = "form-control" })  
  52.                 </div>  
  53.             </div>  
  54.   
  55.             <div class="form-group">  
  56.                 @Html.LabelFor(model => model.IP, new { @class = "col-lg-1 control-label" })  
  57.                 <div class="col-lg-9">  
  58.                     @Html.DisplayFor(model => model.IP, new { @class = "form-control" })  
  59.                 </div>  
  60.             </div>  
  61.   
  62.             @using (Html.BeginForm())  
  63.             {  
  64.                 <div class="form-group">  
  65.                     <div class="col-lg-1"></div>  
  66.                     <div class="col-lg-9">  
  67.                         <input type="submit" value="Delete" class="btn btn-danger" />  
  68.                         @Html.ActionLink("Back to List", "Index", null, new { @class = "btn btn-success" })  
  69.                     </div>  
  70.                 </div>  
  71.             }  
  72.         </div>  
  73.     </div>  
  74. </div> 




Figure 1.8 Delete a Book View.

Conclusion

This article introduced the generic repository pattern with unit of work. I used bootstrap CSS and JavaScript for the user interface design in this application. What do you think about this article? Please provide your feedback.


Similar Articles