Repository Pattern in MVC

1). Create A table “BookTbl” in the database.

CRUD operation in MVC with Repository Pattern

CRUD operation in MVC with Repository Pattern

2). Open Visual Studio and create a new project any name like “RepositoryFst”

And add a new folder into the Model Folder like “DAL”. Here DAL means Data Access Layer and adds to different class file in this folder first add an interface file and second a normal class file like this.

RightClick on ModelFolder -> ADD -> New Folder -> DAL(name).

Select DALfolder -> RightClick -> Add -> New item -> Interface -> IBookRepository.cs(name).

Select DALfolder -> RightClick -> Add -> New item -> Class -> BookRepository.cs(name).

CRUD operation in MVC with Repository Pattern

3). Select Model Folder and RightClick on it. Then fallow it-

Select ModelFolder -> Add -> NewItem -> Data -> ADO.Net Entity Data Model

CRUD operation in MVC with Repository Pattern

CRUD operation in MVC with Repository Pattern

CRUD operation in MVC with Repository Pattern

CRUD operation in MVC with Repository Pattern

4). IBookRepository.cs

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RepositoryFst.Models.DAL
{
    interface IBookRepository
    {
        IEnumerable<BookTbl> GetBooks();
        BookTbl GetBookByID(int bookId);
        void InsertBook(BookTbl book);
        void DeleteBook(int bookId);
        void UpdateBook(BookTbl book);
        void Save();
    }
}

5). BookRepository.cs

using System;

using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace RepositoryFst.Models.DAL
{
    public class BookRepository : IBookRepository
    {
        private DataContext _context;

        public BookRepository(DataContext context)
        {
            _context = context;
        }

        public IEnumerable<BookTbl> GetBooks()
        {
            return _context.BookTbls.ToList();
        }

        public BookTbl GetBookByID(int bookId)
        {
            return _context.BookTbls.Find(bookId);
        }

        public void InsertBook(BookTbl book)
        {
            _context.BookTbls.Add(book);
        }

        public void DeleteBook(int bookId)
        {
            BookTbl book = _context.BookTbls.Find(bookId);
            _context.BookTbls.Remove(book);
        }

        public void UpdateBook(BookTbl book)
        {
            _context.Entry(book).State = EntityState.Modified;
        }

        public void Save()
        {
            _context.SaveChanges();
        }
    }
}

6). HomeController.cs

(add this file in controller folder)

using RepositoryFst.Models;
using RepositoryFst.Models.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace RepositoryFst.Controllers
{
    public class HomeController : Controller
    {
        private IBookRepository interfaceobj;
        public HomeController()
        {
            interfaceobj = new BookRepository(new DataContext());
        }
        public ActionResult Index()
        {
            var data = from m in interfaceobj.GetBooks() select m;
            return View(data);
        }
        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(BookTbl book)
        {
            interfaceobj.InsertBook(book);
            interfaceobj.Save();
            return RedirectToAction("Index");
        }
        public ActionResult Details(int id)
        {
            BookTbl b = interfaceobj.GetBookByID(id);
            return View(b);
        }
        public ActionResult Delete(int id)
        {
            interfaceobj.DeleteBook(id);
            interfaceobj.Save();
            return RedirectToAction("Index");
        }
        public ActionResult Edit(int id)
        {
            BookTbl B = interfaceobj.GetBookByID(id);
            return View(B);
        }
        [HttpPost]
        public ActionResult Edit(int id, BookTbl book)
        {
            interfaceobj.UpdateBook(book);
            interfaceobj.Save();
            return RedirectToAction("Index");
        }
    }
}

7). Add Index View for display all data from that table.

CRUD operation in MVC with Repository Pattern

@model IEnumerable<RepositoryFst.Models.BookTbl>
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.BookName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.BookAuthor)
        </th>
        <th></th>
    </tr>
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.BookName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.BookAuthor)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>     </tr>
}
</table>

8). Details View

CRUD operation in MVC with Repository Pattern

@model RepositoryFst.Models.BookTbl
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Details</title>
</head>
<body>
    <fieldset>
        <legend>BookTbl</legend>
        <div class="display-label">
             @Html.DisplayNameFor(model => model.BookName)
        </div>
        <div class="display-field">
            @Html.DisplayFor(model => model.BookName)
        </div>
        <div class="display-label">
             @Html.DisplayNameFor(model => model.BookAuthor)
        </div>
        <div class="display-field">
            @Html.DisplayFor(model => model.BookAuthor)
        </div>
    </fieldset>
    <p>
        @Html.ActionLink("Edit", "Edit", new { id=Model.ID }) |
        @Html.ActionLink("Back to List", "Index")
    </p>
</body>
</html>

9). Add View(For Insert record)

CRUD operation in MVC with Repository Pattern

@model RepositoryFst.Models.BookTbl
@{
    ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>BookTbl</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.BookName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.BookName)
            @Html.ValidationMessageFor(model => model.BookName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.BookAuthor)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.BookAuthor)
            @Html.ValidationMessageFor(model => model.BookAuthor)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>

10). Delete Record view

CRUD operation in MVC with Repository Pattern

@model RepositoryFst.Models.BookTbl
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Delete</title>
</head>
<body>
    <h3>Are you sure you want to delete this?</h3>
    <fieldset>
        <legend>BookTbl</legend>
        <div class="display-label">
             @Html.DisplayNameFor(model => model.BookName)
        </div>
        <div class="display-field">
            @Html.DisplayFor(model => model.BookName)
        </div>
        <div class="display-label">
             @Html.DisplayNameFor(model => model.BookAuthor)
        </div>
        <div class="display-field">
            @Html.DisplayFor(model => model.BookAuthor)
        </div>
    </fieldset>
    @using (Html.BeginForm()) {
        <p>
            <input type="submit" value="Delete" /> |
            @Html.ActionLink("Back to List", "Index")
        </p>
    }
</body>
</html>

11). Edit/Update Record view

@model RepositoryFst.Models.BookTbl

@{     Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Edit</title>
</head>
<body>
    <script src="~/Scripts/jquery-1.7.1.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true)
        <fieldset>
            <legend>BookTbl</legend>
            @Html.HiddenFor(model => model.ID)
            <div class="editor-label">
                @Html.LabelFor(model => model.BookName)
            </div>             <div class="editor-field">
                @Html.EditorFor(model => model.BookName)
                @Html.ValidationMessageFor(model => model.BookName)
            </div>
            <div class="editor-label">
                @Html.LabelFor(model => model.BookAuthor)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.BookAuthor)
                @Html.ValidationMessageFor(model => model.BookAuthor)
            </div>
            <p>
                <input type="submit" value="Save" />
            </p>
        </fieldset>
    }
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>


  Modified On Sep-05-2018 10:53:25 PM

Leave Comment