CRUD Operation Using Repository Unit Of Work Pattern

Step 1 - Create new ASP.NET MVC Empty project, using VS 2013.

Step 2 - Add new project by right clicking on project, adding class library, and giving name to it.

Step 3 - 
Create one database using SQL Server with below script.
  1. CREATE TABLE [dbo].[UserDetails](  
  2. [Id] [int] IDENTITY(1,1) NOT NULL,  
  3. [Name] [varchar](50) NULL,  
  4. [Address] [varchar](50) NULL,  
  5. [City] [varchar](50) NULL,  
  6. CONSTRAINT [PK_UserDetails] PRIMARY KEY CLUSTERED  
  7. (  
  8. [Id] ASC  
  9. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  10. ON [PRIMARY]   
  11.   
Step 4 - Now, create EDMX from our Database. Just right click on Infrastructure, add New Item => Select on ADO.NET Entity Data Model from data template, and give name to it. Click on Next.
 
Select Generate from Database, click on Next button. Now, give New connection string and select your database, Click OK.

 

It will automatically take entity name. Click on Next and select tables to include the database object in your Model. Then, click on Finish. You will see the edmx as,

 

Step 5 - Also, add one new class library for Repository pattern. Add reference of Infrastructure dll and add Entity Framework from NuGet package.

Step 6 -
 Now, create GenericRepository, IGenericRepository, UnitOfWork classes and add appropriate codes to it, as follows.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.Entity;  
  5. using System.Linq;  
  6. using System.Linq.Expressions;  
  7. using System.Text;  
  8. using System.Threading.Tasks;  
  9.   
  10. namespace Repository  
  11. {  
  12.     public interface IGenericRepository<T> where T : class  
  13.     {  
  14.         IEnumerable<T> GetAll(Expression<Func<T, bool>> filter = null,  
  15.             Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,  
  16.             params Expression<Func<T, object>>[] np);  
  17.   
  18.         T GetByID(object id);  
  19.   
  20.         void Insert(T e);  
  21.   
  22.         void Delete(object id);  
  23.   
  24.         void Delete(T eDlt);  
  25.   
  26.         void Update(T eUpdt);  
  27.   
  28.         void Save();  
  29.   
  30.         T GetSingle(Expression<Func<T, bool>> where, params Expression<Func<T, object>>[] np);  
  31.     }  

Now, add the below code into a UnitOfWork class.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Infrastructure;  
  7. using Repository.GenericRepository;  
  8.   
  9. namespace Repository.GenericRepository  
  10. {  
  11.     public class UnitOfWork : IDisposable  
  12.     {  
  13.         private CRUD_OperationEntities context = new CRUD_OperationEntities();  
  14.         private IGenericRepository<UserDetail> userRepository;  
  15.         public IGenericRepository<UserDetail> UserRepository  
  16.         {  
  17.             get  
  18.             {  
  19.                 return userRepository ?? (userRepository = new GenericRepository<UserDetail>(context));  
  20.             }  
  21.         }  
  22.     }  

Step 7 - Add connection string in App config of Repository class library as well as in web config file of our main project. 
  1. <connectionStrings>  
  2.     <add name="CRUD_OperationEntities" connectionString="metadata=res://*/CRUDOperation.csdl|res://*/CRUDOperation.ssdl|res://*/CRUDOperation.msl;provider=System.Data.SqlClient;provider connection string="data source=RUPESH-PC\SA;initial catalog=CRUD_Operation;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />  
  3.   </connectionStrings> 
Step 8 - Now, create one Home Controller in application. First, we will create one IndexViewModel by adding properties and constructor in it. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace CRUD_Using_Repository_Pattern.ViewModel  
  7. {  
  8.     public class IndexViewModel  
  9.     {  
  10.         private Infrastructure.UserDetail x;  
  11.   
  12.         public IndexViewModel()  
  13.         { }  
  14.   
  15.         public IndexViewModel(Infrastructure.UserDetail user)  
  16.         {  
  17.             Id = user.Id;  
  18.             Name = user.Name;  
  19.             Address = user.Address;  
  20.             City = user.City;  
  21.         }  
  22.   
  23.         public int Id { get; set; }  
  24.         public string Name { get; set; }  
  25.         public string Address { get; set; }  
  26.         public string City { get; set; }  
  27.     }  

Add the below code in Home Controller to perform the CRUD operation.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using Infrastructure;  
  7. using Repository.GenericRepository;  
  8. using CRUD_Using_Repository_Pattern.ViewModel;  
  9.   
  10. namespace CRUD_Using_Repository_Pattern.Controllers  
  11. {  
  12.     public class HomeController : Controller  
  13.     {  
  14.         protected UnitOfWork UnitoffWork { get; private set; }  
  15.         public HomeController()  
  16.         {  
  17.             UnitoffWork = new UnitOfWork();  
  18.         }  
  19.           
  20.         public ActionResult Index()  
  21.         {  
  22.             var user = UnitoffWork.UserRepository.GetAll().Select(x => new IndexViewModel(x));  
  23.             return View(user);  
  24.         }  
  25.   
  26.         public ActionResult Add()  
  27.         {  
  28.             return PartialView("_Add");  
  29.         }  
  30.   
  31.         [HttpPost]  
  32.         public ActionResult Create(IndexViewModel user)  
  33.         {  
  34.             if (user != null)  
  35.             {  
  36.                 UserDetail objUser = new UserDetail();  
  37.                 objUser.Name = user.Name.ToString();  
  38.                 objUser.Address = user.Address.ToString();  
  39.                 objUser.City = user.City.ToString();  
  40.                 UnitoffWork.UserRepository.Insert(objUser);  
  41.                 UnitoffWork.UserRepository.Save();  
  42.             }  
  43.             return RedirectToAction("Index");  
  44.         }  
  45.   
  46.         [HttpGet]  
  47.         public ActionResult Edit(int Id)  
  48.         {  
  49.             var user = UnitoffWork.UserRepository.GetSingle(c => c.Id == Id);  
  50.             return PartialView("_Edit"new IndexViewModel(user));  
  51.         }  
  52.   
  53.         [HttpPost]  
  54.         public ActionResult Update(IndexViewModel user)  
  55.         {  
  56.             UserDetail objUser = new UserDetail();  
  57.             if (user.Name != null)  
  58.             {  
  59.                 var count = UnitoffWork.UserRepository.GetAll().Where(a => a.Id == user.Id).Count();  
  60.                 if (count != 0)  
  61.                 {  
  62.                     objUser.Id = user.Id;  
  63.                     objUser.Name = user.Name.ToString();  
  64.                     objUser.Address = user.Address.ToString();  
  65.                     objUser.City = user.City.ToString();  
  66.                     UnitoffWork.UserRepository.Update(objUser);  
  67.                     UnitoffWork.UserRepository.Save();  
  68.                 }  
  69.             }  
  70.             return RedirectToAction("Index");  
  71.         }  
  72.         [HttpGet]  
  73.         public ActionResult Delete(int Id)  
  74.         {  
  75.             UserDetail objUser = new UserDetail();  
  76.             var user = UnitoffWork.UserRepository.GetSingle(c => c.Id == Id);  
  77.             if(user != null)  
  78.             {  
  79.                 objUser.Id = user.Id;  
  80.                 UnitoffWork.UserRepository.Delete(objUser);  
  81.                 UnitoffWork.UserRepository.Save();  
  82.             }  
  83.             return RedirectToAction("Index");  
  84.         }  
  85.     }  

Create Index View for the Index action method as,
  1. @model IEnumerable<CRUD_Using_Repository_Pattern.ViewModel.IndexViewModel>  
  2.     @{  
  3.         Layout = null;  
  4.     }  
  5.   
  6. <a href="@Url.Action("Add", "Home")" style="margin-left:12%" id="addNew">Add New</a>  
  7.   
  8.     <!DOCTYPE HTML>  
  9.   
  10.     <html>  
  11.     <head>  
  12.         <meta name="viewport" content="width=device-width" />  
  13.         <title>Index</title>  
  14.     </head>  
  15.     <body>  
  16.         <div>  
  17.             <table style="border: 1px solid; width: 60%; margin-left:20%">  
  18.                 <thead>  
  19.                     <tr>  
  20.                         <th width="30%" style="text-align:center">Name</th>  
  21.                         <th width="30%" style="text-align:center">Address</th>  
  22.                         <th width="30%" style="text-align:center">City</th>  
  23.                         <th width="15%" style="text-align:center">Action</th>  
  24.                         <th width="15%" style="text-align:center">Action</th>  
  25.                     </tr>  
  26.                 </thead>  
  27.                 <tbody style="border:1px solid;">  
  28.                     @if (Model != null)  
  29.                     {  
  30.                         foreach (var item in Model)  
  31.                         {  
  32.                             <tr>  
  33.                                 <td style="text-align:center">  
  34.                                     @item.Name  
  35.                                 </td>  
  36.                                 <td style="text-align:center">  
  37.                                     @item.Address  
  38.                                 </td>  
  39.                                 <td style="text-align:center">  
  40.                                     @item.City  
  41.                                 </td>  
  42.                                 <td>  
  43.                                     <a href="@Url.Action("Edit", "Home",new { Id = item.Id })" onclick="">Edit</a>  
  44.                                </td>  
  45.                                 <td>  
  46.                                     <a href="@Url.Action("Delete", "Home",new { Id = item.Id })" onclick="">Delete</a>  
  47.                                 </td>  
  48.                             </tr>  
  49.                         }  
  50.                     }  
  51.                 </tbody>  
  52.             </table>  
  53.         </div>  
  54.     </body>  
  55.    </html> 
Create Partial View _Add for Add action method as,
  1. @model CRUD_Using_Repository_Pattern.ViewModel.IndexViewModel  
  2.   
  3. @using (Html.BeginForm("Create", "Home", FormMethod.Post))  
  4. {  
  5.    <div style="margin-left:15%">  
  6.        <div>  
  7.            @Html.LabelFor(model => model.Name)     
  8.            @Html.EditorFor(model => model.Name)  
  9.        </div>  
  10.        <br />  
  11.        <div>  
  12.            @Html.LabelFor(model => model.Address)  
  13.            @Html.EditorFor(model => model.Address)  
  14.        </div>  
  15.        <br />  
  16.        <div>  
  17.            @Html.LabelFor(model => model.City)         
  18.            @Html.EditorFor(model => model.City)  
  19.        </div>  
  20.        <br />  
  21.        <input type="submit" value="Add" />  
  22.    </div>  

Create Partial View _Edit for Edit Action as,
  1. @model CRUD_Using_Repository_Pattern.ViewModel.IndexViewModel  
  2.   
  3. @using (Html.BeginForm("Update", "Home", FormMethod.Post))  
  4. {  
  5.     <div style="margin-left:15%">  
  6.         <div>  
  7.             @Html.LabelFor(model => model.Id)         
  8.             @Html.TextBoxFor(model => model.Id, new { @readonly = "readonly" })  
  9.         </div>  
  10.         <br />  
  11.         <div>  
  12.             @Html.LabelFor(model => model.Name)     
  13.             @Html.EditorFor(model => model.Name)  
  14.         </div>  
  15.         <br />  
  16.         <div>  
  17.             @Html.LabelFor(model => model.Address)  
  18.             @Html.EditorFor(model => model.Address)  
  19.         </div>  
  20.         <br />  
  21.         <div>  
  22.             @Html.LabelFor(model => model.City)         
  23.             @Html.EditorFor(model => model.City)  
  24.         </div>  
  25.         <br />  
  26.         <input type="submit" value="Update" />  
  27.     </div>  

Now, if we run the application, you will see the list of all users.


Now, click on Add New to add new record.

 
After adding new record, click on edit of Jeetendra to update surname.


After updating the record, you will see.

 

Now, click on delete the record of Amit K,



After deleting the record, our list of all users will be as shown below.

 
Summary - This article will help fresher candidates to understand CRUD operations using Repository Pattern, UnitOfWork.


Similar Articles