Download the complete code from here : Repositry and Unit of Work

Creating the User Repository Class

In the DAL folder, create an interface IUserRepository and write the following code:

using Batua.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace Batua.DAL
{
    public interface IUserRepository : IDisposable
    {
        IEnumerable<User> GetUsers();
        User GetUserByID(int userID);
        void InsertUser(User user);
        void DeleteUser(int userID);
        void UpdateUser(User user);
        void Save();
    }
}

The code declares a set of CRUD methods. Now in the same folder create a class named UserRepository and write the following code which implements the interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Batua.Models;
 
namespace Batua.DAL
{
    public class UserRepository : GenericRepository<User>
//IUserRepository, IDisposable     {         //private BatuaContext context;         //public UserRepository(BatuaContext context)         //{         //    this.context = context;         //}         public UserRepository(BatuaContext context)         : base(context)         {         }         public void DeleteUser(int userID)         {             User user = context.User.Find(userID);             context.User.Remove(user);         }         public User GetUserByID(int userID)         {             return context.User.Find(userID);         }         public IEnumerable<User> GetUsers()         {             return context.User.ToList();         }         public void InsertUser(User user)         {             context.User.Add(user);         }         public void UpdateUser(User user)         {             context.Entry(user).State 
= System.Data.Entity.EntityState.Modified;         }         public void Save()         {             context.SaveChanges();         }         private bool disposed = false;         protected virtual void Dispose(bool disposing)         {             if (!this.disposed)             {                 if (disposing)                 {                     context.Dispose();                 }             }             this.disposed = true;         }         public void Dispose()         {             Dispose(true);             GC.SuppressFinalize(this);         }     } }

The repository implements IDisposable interface and disposes the database context.

 

Now write the following code inside UserController

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Batua.DAL;
using Batua.Models;
 
namespace Batua.Controllers
{
    public class UsersController : Controller
    {
        private UnitOfWork unitofWork = new UnitOfWork();
        //private IUserRepository userRepository;
 
        public UsersController()
        {
         //   this.userRepository = 
new UserRepository(new BatuaContext());
        }         //public UsersController(IUserRepository userRepository)         //{         //    this.userRepository = userRepository;         //}        // private BatuaContext db = new BatuaContext();         // GET: Users         public ActionResult Index()         {             //return View(userRepository.GetUsers().ToList());             var user = unitofWork.UserRepository.GetUsers().ToList();             return View(user.ToList());         }         // GET: Users/Details/5         public ActionResult Details(int? id)         {             if (id == null)             {                 return new HttpStatusCodeResult(
HttpStatusCode.BadRequest);             }             // User user = userRepository.GetUserByID((int)(id));             User user = unitofWork.UserRepository.GetByID((int)id);             if (user == null)             {                 return HttpNotFound();             }             return View(user);         }         // GET: Users/Create         public ActionResult Create()         {             return View();         }         // POST: Users/Create         // To protect from overposting attacks, 
please enable the specific properties you want to bind to, for 
        // more details see 
https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]         [ValidateAntiForgeryToken]         public ActionResult Create(
[
Bind(Include = "Name,Mobile,Email")] User user)         {             try             {                 if (ModelState.IsValid)                 {                     //userRepository.InsertUser(user);                     //userRepository.Save();                     unitofWork.UserRepository.Insert(user);                     unitofWork.Save();                     return RedirectToAction("Index");                 }             }             catch (DataException ex)             {                 ModelState.AddModelError(ex.Message,
 
"Unable to save changes. Try again..");             }             return View(user);         }         // GET: Users/Edit/5         public ActionResult Edit(int? id)         {             if (id == null)             {                 return new 
HttpStatusCodeResult(HttpStatusCode.BadRequest);             }             //  User user = userRepository.GetUserByID((int)id);             User user = unitofWork.UserRepository.GetByID((int) id);             unitofWork.Save();             if (user == null)             {                 return HttpNotFound();             }             return View(user);         }         // POST: Users/Edit/5         // To protect from overposting attacks, 
please enable the specific properties you want to bind to, for 
        // more details see 
https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]         [ValidateAntiForgeryToken]         public ActionResult Edit(
[
Bind(Include = "UserID,Name,Mobile,Email")] User user)         {             try             {                 if (ModelState.IsValid)                 {                     //userRepository.UpdateUser(user);                     //userRepository.Save();                     unitofWork.UserRepository.Update(user);                     unitofWork.Save();                     return RedirectToAction("Index");                 }             }             catch (DataException ex)             {                 ModelState.AddModelError(ex.Message,
 
"Unable to save changes. Try again");             }             return View(user);         }         // GET: Users/Delete/5         public ActionResult Delete(int? id)         {             if (id == null)             {                 return 
new HttpStatusCodeResult(HttpStatusCode.BadRequest);             }             //  User user = userRepository.GetUserByID((int)id);             User user = unitofWork.UserRepository.GetByID((int)id);                          if (user == null)             {                 return HttpNotFound();             }             return View(user);         }         // POST: Users/Delete/5         [HttpPostActionName("Delete")]         [ValidateAntiForgeryToken]         public ActionResult DeleteConfirmed(int id)         {             //User user = userRepository.GetUserByID((int)id);             //userRepository.DeleteUser((int)id);             //userRepository.Save();             User user = unitofWork.UserRepository.GetByID((int)id);             unitofWork.UserRepository.Delete((int)id);             unitofWork.Save();             return RedirectToAction("Index");         }         protected override void Dispose(bool disposing)         {             if (disposing)             {                 // userRepository.Dispose();                 unitofWork.Dispose();             }             base.Dispose(disposing);         }     } }

 

Creating Unit of Work class

The unit of work class serves one purpose: to make sure that when you use multiple repositories, they share a single database context. 

That way, when a unit of work is complete you can call the SaveChanges method on that instance of the context and ensures that all the related

changes will be coordinated. It needs Save method and a property for each repository. Each repository property returns a repository instance that 

has been instantiated using the same database context instance as the other repository instances.

In the DAL folder create a class file named UnitOfWork.cs and write the following code:

using Batua.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace Batua.DAL
{
    public class UnitOfWork : IDisposable
    {
        private BatuaContext context = new BatuaContext();
        private UserRepository userRepository;
        
        public UnitOfWork()
        {
            
        }
 
        public UserRepository UserRepository
        {
            get
            {
 
                if (this.userRepository == null)
                {
                    this.userRepository = new UserRepository(context);
                }
                return userRepository;
            }
        }
 
 
        public void Save()
        {
            context.SaveChanges();
        }
 
        private bool disposed = false;
 
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    context.Dispose();
                }
            }
            this.disposed = true;
        }
 
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}

Changes will also need to be done on Controller side as well to use UnitOfWork.

 Download the complete code from here : Repositry and Unit of Work

NOTE : Please refer to the code inside the controller which is commented out. Current code works with Unit of Work pattern. You can also run it with Repository pattern for which you need to uncomment the code save the changes. Also you need to comment out the Unit of Work part in the code .

blog comments powered by Disqus