Repository Pattern

Repository Pattern with very easy Code Example!



In this video, I have explained the following:
We will learn Using Book Management…
  • Repository Design patterns (What & Why)
  • Repository Design patterns structure
  • Code go through
  • Advantages
  • Basic understanding of object oriented concepts will be helpful

Suggested Videos:
Repository Patterns (What & Why)
  • Repository design pattern implement de-coupling of the business logic and the data access layers in your application also implement the SOC without having any knowledge of data retrieval and stored logic.
  • Repository pattern C# also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers.
  • Example: you may have a repository that stores and retrieves data from an in-memory collection or retrieves data from a database like SQL Server or SharePoint list, or a Web service.
Repository Pattern with MVC (Code First)

Advantage
  • Different Data Source swapping: eg- In one case, you want to retrieve data from in-memory or sql database, in other case you may need to retrieve from API.
  • Highly Testable: Repository systems are good for testing. You create an interface for your repository, and you reference the interface for it when you are making the object. Then you can later make a fake object (using moq for instance) which implements that interface.

Practical Implementation:

Step1 - Create basic MVC application with name Mvc4App
Step2 - Create a class with Name Book.cs in Models folder and paste the following code
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace Mvc4App.Models
{
    public class Book
    {
        public int BookId { get; set; }   
        public string BookTitle { get; set; }     
        public string Standard { get; set; }   
        public string Subject { get; set; }
        public string Author { get; set; }
    }
}

Step3 - Create a class with Name BookContext.cs in Models folder and paste the following code
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace Mvc4App.Models
{
    public class BookContext : DbContext
    {
        public BookContext() : base("DefaultConnection") { }
        public DbSet<Book> Books
        {
            get;
            set;
        }
    }
}

Step4 - Create a folder with name Repository under Root
Step5 - Create a Class/Interface with Name IBookRepository.cs in Models folder and paste the following code
using Mvc4App.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Mvc4App.Repository
{
    public interface IBookRepository : IDisposable
    {
        IEnumerable<Book> GetAllBook();
        Book GetBookById(int bookId);
        int AddBook(Book bookEntity);
        int UpdateBook(Book bookEntity);
        void DeleteBook(int bookId);
    }
}

Step6 - Create a Class with Name BookRepository.cs in Models folder and paste the following code
using Mvc4App.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace Mvc4App.Repository
{
    public class BookRepository:IBookRepository
    {
        private readonly BookContext _context;
        public BookRepository(BookContext context)
        {
            _context = context;
        }
        public IEnumerable<Book> GetAllBook()
        {
            return _context.Books.ToList();
        }
        public Book GetBookById(int bookId)
        {
            return _context.Books.Find(bookId);
        }
        public int AddBook(Book bookEntity)
        {
            int result = -1;
            if (bookEntity != null)
            {
                _context.Books.Add(bookEntity);
                _context.SaveChanges();
                result = bookEntity.BookId;
            }
            return result;
        }
        public int UpdateBook(Book bookEntity)
        {
            int result = -1;
            if (bookEntity != null)
            {
                _context.Entry(bookEntity).State = EntityState.Modified;
                _context.SaveChanges();
                result = bookEntity.BookId;
            }
            return result;
        }
        public void DeleteBook(int bookId)
        {
            Book BookEntity = _context.Books.Find(bookId);
            _context.Books.Remove(BookEntity);
            _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);
        }
    }
}
Step7 - Create a Controller with Name BookController.cs in Controllers folder and paste the following code
using Mvc4App.Models;
using Mvc4App.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Mvc4App.Controllers
{
    public class BookController : Controller
    {
        private IBookRepository _bookRepository;
        public BookController()
        {
            _bookRepository = new BookRepository(new Models.BookContext());
        }
        public BookController(IBookRepository employeeRepository)
        {
            _bookRepository = employeeRepository;
        }
        public ActionResult Index()
        {
            var model = _bookRepository.GetAllBook();
            return View(model);
        }
        public ActionResult AddBook()
        {
            if (TempData["Failed"] != null)
            {
                ViewBag.Failed = "Add Book Failed";
            }
            return View();
        }

        [HttpPost]
        public ActionResult AddBook(Book model)
        {
            if (ModelState.IsValid)
            {
                int result = _bookRepository.AddBook(model);
                if (result > 0)
                {
                    return RedirectToAction("Index", "Book");
                }
                else
                {
                    TempData["Failed"] = "Failed";
                    return RedirectToAction("AddBook", "Book");
                }
            }
            return View();
        }

        public ActionResult EditBook(int BookId)
        {
            if (TempData["Failed"] != null)
            {
                ViewBag.Failed = "Edit Book Failed";
            }
            Book model = _bookRepository.GetBookById(BookId);
            return View(model);
        }

        [HttpPost]
        public ActionResult EditBook(Book model)
        {
            if (ModelState.IsValid)
            {
                int result = _bookRepository.UpdateBook(model);
                if (result > 0)
                {
                    return RedirectToAction("Index", "Book");
                }
                else
                {
                    return RedirectToAction("Index", "Book");
                }
            }
            return View();
        }

        public ActionResult DeleteBook(int BookId)
        {
            Book model = _bookRepository.GetBookById(BookId);
            return View(model);
        }

        [HttpPost]
        public ActionResult DeleteBook(Book model)
        {
            if (TempData["Failed"] != null)
            {
                ViewBag.Failed = "Delete Book Failed";
            }
           _bookRepository.DeleteBook(model.BookId);
            return RedirectToAction("Index", "Book");
        }
    }
}

Step8 - Create 4 views for all 4 actions Index.cshtml,AddBook.cshtml,EditBook.cshtml and DeleteBook.cshtml
Step9 - In Index.cshtml, paste the following code
@model IEnumerable < Mvc4App.Models.Book >
   @{
        ViewBag.Title = "Index";
    }
    <div align = "center">
    <h3> Book Management </h3>
    <span> <a href="@Url.Action("AddBook","Book")">Add Book</a></span >
    <br/>
    <br/>
    <table cellpadding = "5" border = "1">
        <tr style = "background-color:#808080; color:white;">
            <td>BookId </td>
            <td>BookTitle </td>
            <td>Standard </td>
            <td>Subject</td>
            <td>Author </td>
        </tr>
        @foreach(var book in Model) {
        <tr>
            <td>@book.BookId </td>
            <td>@book.BookTitle</td>
            <td>@book.Standard </td>
            <td>@book.Subject </td>
            <td>@book.Author </td>
            <td>
            <a href = "@Url.Action("EditBook", "Book", new { @BookId = book.BookId })"> Edit </a>
            <a href = "@Url.Action("DeleteBook", "Book", new { @BookId = book.BookId })"> Delete </a>
            </td>
        </tr> 
        }
   </table>
    </div>
Step10 - In AddBook.cshtml, paste the following code
@model Mvc4App.Models.Book
@{
    ViewBag.Title ="AddBook";
}

<div align="center">
    <h3>Book Management</h3><br/>
    <b>Add New Book</b><br/>
    <br/>
    @using(Html.BeginForm("AddBook","Book",FormMethod.Post)) {
        <table>
            <tr><td colspan ="2">
            @if (ViewBag.Failed != null) {
                <span style="color:red;">@ViewBag.Failed</span>
            }
            </td></tr>
            <tr>
            <td>@Html.LabelFor(e => e.BookTitle) </td>
            <td>
            @Html.TextBoxFor(e => e.BookTitle) <br/>
            @Html.ValidationMessageFor(e => e.BookTitle, null, new {style = "color:red;"}) </td></tr>
            <tr>
            <td>@Html.LabelFor(e => e.Standard) </td>
            <td>
            @Html.TextBoxFor(e => e.Standard) <br/>
            @Html.ValidationMessageFor(e => e.Standard, null, new {style = "color:red;"}) </td></tr>
            <tr>
            <td>@Html.LabelFor(e => e.Subject) </td>
            <td>
            @Html.TextBoxFor(e => e.Subject) <br/>
            @Html.ValidationMessageFor(e => e.Subject, null, new {style = "color:red;"}) </td></tr>
            <tr>
            <td>@Html.LabelFor(e => e.Author) </td>
            <td>
            @Html.TextBoxFor(e => e.Author) <br/>
            @Html.ValidationMessageFor(e => e.Author, null, new {style = "color:red;"}) </td></tr>
            <tr>
            <tr>
            <td colspan="2" align="center"><br/>
            <input type ="submit" value = "Submit"/>
            </td>
            </tr>             
        </table>
    }
</div>

Step11 - In EditBook.cshtml, paste the following code
@model Mvc4App.Models.Book
@{ 
    ViewBag.Title = "Edit Book";
}
<div align="center">
    <h3>Book Management</h3> <br/>
    <b>Edit Book </b> <br/>
    <br/>
    @using(Html.BeginForm("EditBook", "Book", FormMethod.Post))
    {
        @Html.HiddenFor(e => e.BookId)
            <table>
            <tr>
            <td colspan="2">
            @if(ViewBag.Failed!= null) {
                <span style="color:red;">@ViewBag.Failed</span>
            } </td></tr>
            <tr><td>
            @Html.LabelFor(e => e.BookTitle) </td>             
            <td>
            @Html.TextBoxFor(e => e.BookTitle) <br/>
            @Html.ValidationMessageFor(e => e.BookTitle, null, new { style="color:red;" }) </td>
            </tr>
            <tr>
            <td>
            @Html.LabelFor(e => e.Standard) </td>
            <td>
            @Html.TextBoxFor(e => e.Standard) <br/>
            @Html.ValidationMessageFor(e => e.Standard, null, new{ style="color:red;" }) </td>
            </tr>
            <tr><td>
            @Html.LabelFor(e => e.Subject) </td>
            <td>
            @Html.TextBoxFor(e => e.Subject) <br/>
            @Html.ValidationMessageFor(e => e.Subject, null, new{ style="color:red;"})</td>
            </tr>
                <tr><td>
            @Html.LabelFor(e => e.Author) </td>
            <td>
            @Html.TextBoxFor(e => e.Author) <br/>
            @Html.ValidationMessageFor(e => e.Author, null, new{ style="color:red;"})</td>
           </tr>
           <tr>
            <td colspan="2" align="center">
            <br/>
            <input type="submit" value="Update"/>
            </td> </tr>
            </table>
    } </div>
Step12 - In DeleteBook.cshtml, paste the following code
@model Mvc4App.Models.Book
@{
    ViewBag.Title = "Delete Book";
}
<div align ="center">
    <h3> Book Management </h3> <br/>
    @using(Html.BeginForm("DeleteBook", "Book", FormMethod.Post))
    {
        @Html.HiddenFor(e => e.BookId)
            <table border="1" cellpadding="10">
            <tr>
            <td colspan="2" align="center">
            <b>Delete Book </b>
        @if(ViewBag.Failed != null) {
            <span style ="color:red;"> @ViewBag.Failed </span>
            } </td> </tr>
                <tr>
           <td>
            @Html.LabelFor(e => e.BookTitle) </td>
                    <td>
            @Html.TextBoxFor(e => e.BookTitle, new{ @readonly="readonly" })
        </td> </tr> <tr>
            <td>
            @Html.LabelFor(e => e.Standard) </td>
            <td>
            @Html.TextBoxFor(e => e.Standard, new { @readonly="readonly" })
        </td> </tr>
                <tr>
            <td>
            @Html.LabelFor(e => e.Subject) </td>
        <td>
            @Html.TextBoxFor(e => e.Subject, new { @readonly="readonly" })
        </td></tr>
                <tr>
            <td>
            @Html.LabelFor(e => e.Author) </td>
        <td>
            @Html.TextBoxFor(e => e.Author, new { @readonly="readonly" })
        </td></tr>
        <tr>
            <td colspan ="2" align ="center">
            <br/><input type ="submit" value="Delete"/>
            </td></tr>
        </table>
    } </div>
Step13 - Make the following changes in RouteConfig.cs

Step14 - Make the Required changes in Web.congig file

<add name="DefaultConnection" connectionString="data source=(local); database=Yourdbname;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />

Click below to see all these these things in action:


2 comments:

  1. thank you for the clear concept.waiting for the more topics...

    ReplyDelete
    Replies
    1. Thank you very much for taking time to give feedback. This means a lot for us. I am very glad you found the videos useful.

      More Videos can also be found on my YouTube channel. Please subscribe to encourage me create more such videos to help the dev community.
      https://www.youtube.com/TechWebDots

      If you want to receive email alerts, when new videos/post are uploaded, please subscribe to my YouTube channel.

      If you like this post, May I ask you for a favor. I want these tutorials to be helpful for as many people as possible. Please share the link with your friends and family who you think would also benefit from them.

      Happy Coding and Good Luck TechWebDots!

      Delete

Your feedback is important.
Visit www.techwebdots.in