Repository pattern with code first approach in MVC 4

This asp.net mvc 4 tutorial, we will discuss What is Repository Pattern and Repository pattern with code first approach in MVC 4?

What is Repository Pattern?

A Repository separates the business logic from the interaction with data access logic or web service of the application. It acts as an in-memory business object collection. The repository hides the details of how exactly the requested data is being fetched/persisted from/to the database. Use this pattern to keep

  • A single place to make changes to data access
  • A single point responsible for a set of tables
  • It easy to replace a repository with a fake implementation for testing

You may like following asp.net mvc tutorials:

Repository pattern with code first approach in MVC 4

Step 1:

Choose Internet Application template in mvc4 project, create a Contact model.
model: contact.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace CrudRepoPattContact.Models
{
public class Contact
{
[Key] public int id { get; set; }
[Required] [MaxLength(30)] public string name { get; set; }
[RegularExpression(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$" ,ErrorMessage="Invalid Emailid")] public string email { get; set; }
[Column("Phone")] [Display(Name = "Phone number")] public string phoneNo { get; set; }
public string city { get; set; }
}
}

Step 2:

Create a folder named DAL in solution Explorer, create context class, interface for repository and repository implementation class.
DAL folder:
Context Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using CrudRepoPattContact.Models;

namespace CrudRepoPattContact.DAL
{
public class ContactContext : DbContext
{
public ContactContext()
: base("name=ContactConnectionString")
{
}
public DbSet<Contact> Contacts { get; set; }
}
}

In web.config file the connection string is,

<connectionStrings>
<add name="ContactConnectionString" connectionString="data source=MYHOME;Integrated Security=SSPI;Initial Catalog=Contact;" providerName="System.Data.SqlClient" />
</connectionStrings>

IContactReopsitory interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CrudRepoPattContact.Models;
namespace CrudRepoPattContact.DAL
{
public interface IContactReopsitory
{
IEnumerable<Contact> GetContacts();
Contact GetContactByID(int ContId);
void InsertContact(Contact contact);
void DeleteContact(int ContId);
void UpdateContact(Contact contact);
void Save();

}
}

ContactRepository class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using CrudRepoPattContact.Models;
namespace CrudRepoPattContact.DAL
{
public class ContactRepository :IContactReopsitory
{
private ContactContext _context;
public ContactRepository(ContactContext contactContext)
{
this._context = contactContext;
}

public IEnumerable<Contact> GetContacts()
{
return _context.Contacts.ToList();

}
public Contact GetContactByID(int ContId)
{
return _context.Contacts.Find(ContId);

}
public void InsertContact(Contact contact)
{

_context.Contacts.Add(contact);
}
public void DeleteContact(int ContId)
{
Contact contact = _context.Contacts.Find(ContId);
_context.Contacts.Remove(contact);

}
public void UpdateContact(Contact contact)
{
_context.Entry(contact).State = 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);
}
}
}
Repository pattern with code first approach in MVC 4

Step 3:
Create ContactController with Contact model and ContactContext, specify the route of the controller and in RegisterRoutes method in Global.asax file.

Repository pattern with code first approach in MVC 4

ContactController.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CrudRepoPattContact.Models;
using CrudRepoPattContact.DAL;

namespace CrudRepoPattContact.Controllers
{
public class ContactController : Controller
{
private ContactContext db = new ContactContext();

// GET: /Contact/

public ViewResult Index()
{
return View(db.Contacts.ToList());
}

// GET: /Contact/Details/5

public ViewResult Details(int id)
{
Contact contact = db.Contacts.Find(id);
return View(contact);
}

// GET: /Contact/Create

public ActionResult Create()
{
return View();
}

// POST: /Contact/Create

[HttpPost] public ActionResult Create(Contact contact)
{
if (ModelState.IsValid)
{
db.Contacts.Add(contact);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(contact);
}

// GET: /Contact/Edit/5

public ActionResult Edit(int id)
{
Contact contact = db.Contacts.Find(id);
return View(contact);
}

// POST: /Contact/Edit/5

[HttpPost] public ActionResult Edit(Contact contact)
{
if (ModelState.IsValid)
{
db.Entry(contact).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(contact);
}
// GET: /Contact/Delete/5

public ActionResult Delete(int id)
{
Contact contact = db.Contacts.Find(id);
return View(contact);
}

// POST: /Contact/Delete/5

[HttpPost, ActionName("Delete")] public ActionResult DeleteConfirmed(int id)
{
Contact contact = db.Contacts.Find(id);
db.Contacts.Remove(contact);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}

Global.asax.cs

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Contact", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

}

views:
Create.cshtml

@model CrudRepoPattContact.Models.Contact
@{
ViewBag.Title = "Create";
}

<h2>Create</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Contact</legend>

<div class="editor-label">
@Html.LabelFor(model => model.name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.name)
@Html.ValidationMessageFor(model => model.name)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.email)
@Html.ValidationMessageFor(model => model.email)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.phoneNo)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.phoneNo)
@Html.ValidationMessageFor(model => model.phoneNo)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.city)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.city)
@Html.ValidationMessageFor(model => model.city)
</div>

<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>

Delete.cshtml

@model CrudRepoPattContact.Models.Contact
@{
ViewBag.Title = "Delete";
}

<h2>Delete</h2>

<h3>Are you sure you want to delete this?</h3>
<fieldset>
<legend>Contact</legend>

<div class="display-label">
@Html.DisplayNameFor(model => model.name)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.name)
</div>

<div class="display-label">
@Html.DisplayNameFor(model => model.email)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.email)
</div>

<div class="display-label">
@Html.DisplayNameFor(model => model.phoneNo)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.phoneNo)
</div>

<div class="display-label">
@Html.DisplayNameFor(model => model.city)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.city)
</div>
</fieldset>
@using (Html.BeginForm()) {
<p>
<input type="submit" value="Delete" /> |
@Html.ActionLink("Back to List", "Index")
</p>
}

Details.cshtml

@model CrudRepoPattContact.Models.Contact

@{
ViewBag.Title = "Details";
}

<h2>Details</h2>

<fieldset>
<legend>Contact</legend>

<div class="display-label">
@Html.DisplayNameFor(model => model.name)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.name)
</div>

<div class="display-label">
@Html.DisplayNameFor(model => model.email)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.email)
</div>

<div class="display-label">
@Html.DisplayNameFor(model => model.phoneNo)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.phoneNo)
</div>

<div class="display-label">
@Html.DisplayNameFor(model => model.city)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.city)
</div>
</fieldset>
<p>
@Html.ActionLink("Edit", "Edit", new { id=Model.id }) |
@Html.ActionLink("Back to List", "Index")
</p>

Edit.cshtml

@model CrudRepoPattContact.Models.Contact

@{
ViewBag.Title = "Edit";
}

<h2>Edit</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Contact</legend>

@Html.HiddenFor(model => model.id)

<div class="editor-label">
@Html.LabelFor(model => model.name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.name)
@Html.ValidationMessageFor(model => model.name)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.email)
@Html.ValidationMessageFor(model => model.email)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.phoneNo)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.phoneNo)
@Html.ValidationMessageFor(model => model.phoneNo)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.city)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.city)
@Html.ValidationMessageFor(model => model.city)
</div>

<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>

Index.cshtml

@model IEnumerable<CrudRepoPattContact.Models.Contact>

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.name)
</th>
<th>
@Html.DisplayNameFor(model => model.email)
</th>
<th>
@Html.DisplayNameFor(model => model.phoneNo)
</th>
<th>
@Html.DisplayNameFor(model => model.city)
</th>
<th></th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.name)
</td>
<td>
@Html.DisplayFor(modelItem => item.email)
</td>
<td>
@Html.DisplayFor(modelItem => item.phoneNo)
</td>
<td>
@Html.DisplayFor(modelItem => item.city)
</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>
asp.net mvc 4 Repository pattern
asp.net mvc Repository pattern
Repository pattern with code first approach in MVC

You may like following asp.net tutorials:

This tutorial, we learned Repository pattern with code first approach in MVC 4.

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

>