Step 1. Create a new ASP.NET MVC Empty project using VS.
Step 2. Add a new project by right-clicking on the project, adding the class library, and giving a name to it.
Step 3. Create one database using SQL Server with the below script.
CREATE TABLE [dbo].[UserDetails] (
[Id] INT IDENTITY(1,1) NOT NULL,
[Name] VARCHAR(50) NULL,
[Address] VARCHAR(50) NULL,
[City] VARCHAR(50) NULL,
CONSTRAINT [PK_UserDetails] PRIMARY KEY CLUSTERED (
[Id] ASC
) WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
) ON [PRIMARY];
Step 4. Now, create EDMX from our Database. Just right-click on Infrastructure, add New Item => Select ADO.NET Entity Data Model from the data template, and give a name to it. Click on Next.
Select Generate from Database, and click on the Next button. Now, give the New connection string and select your database; click OK.
It will automatically take the 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 the Repository pattern. Add a reference to Infrastructure dll and add Entity Framework from the NuGet package.
Step 6. Now, create GenericRepository, IGenericRepository, and UnitOfWork classes and add appropriate codes to it, as follows.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace Repository
{
public interface IGenericRepository<T> where T : class
{
IEnumerable<T> GetAll(
Expression<Func<T, bool>> filter = null,
Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
params Expression<Func<T, object>>[] np);
T GetByID(object id);
void Insert(T e);
void Delete(object id);
void Delete(T eDlt);
void Update(T eUpdt);
void Save();
T GetSingle(
Expression<Func<T, bool>> where,
params Expression<Func<T, object>>[] np);
}
}
Now, add the code below to a UnitOfWork class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure;
using Repository.GenericRepository;
namespace Repository.GenericRepository
{
public class UnitOfWork : IDisposable
{
private CRUD_OperationEntities context = new CRUD_OperationEntities();
private IGenericRepository<UserDetail> userRepository;
public IGenericRepository<UserDetail> UserRepository
{
get
{
return userRepository ?? (userRepository = new GenericRepository<UserDetail>(context));
}
}
}
}
Step 7. Add a connection string to the app configuration of the repository class library as well as to the web configuration file of our main project.
<connectionStrings>
<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" />
</connectionStrings>
Step 8. Now, create one Home Controller in the application. First, we will create one IndexViewModel by adding properties and constructors to it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CRUD_Using_Repository_Pattern.ViewModel
{
public class IndexViewModel
{
private Infrastructure.UserDetail x;
public IndexViewModel() { }
public IndexViewModel(Infrastructure.UserDetail user)
{
Id = user.Id;
Name = user.Name;
Address = user.Address;
City = user.City;
}
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
}
}
Add the code below in the Home Controller to perform the CRUD operation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Infrastructure;
using Repository.GenericRepository;
using CRUD_Using_Repository_Pattern.ViewModel;
namespace CRUD_Using_Repository_Pattern.Controllers
{
public class HomeController : Controller
{
protected UnitOfWork UnitoffWork { get; private set; }
public HomeController()
{
UnitoffWork = new UnitOfWork();
}
public ActionResult Index()
{
var user = UnitoffWork.UserRepository.GetAll().Select(x => new IndexViewModel(x));
return View(user);
}
public ActionResult Add()
{
return PartialView("_Add");
}
[HttpPost]
public ActionResult Create(IndexViewModel user)
{
if (user != null)
{
UserDetail objUser = new UserDetail
{
Name = user.Name.ToString(),
Address = user.Address.ToString(),
City = user.City.ToString()
};
UnitoffWork.UserRepository.Insert(objUser);
UnitoffWork.UserRepository.Save();
}
return RedirectToAction("Index");
}
[HttpGet]
public ActionResult Edit(int Id)
{
var user = UnitoffWork.UserRepository.GetSingle(c => c.Id == Id);
return PartialView("_Edit", new IndexViewModel(user));
}
[HttpPost]
public ActionResult Update(IndexViewModel user)
{
UserDetail objUser = new UserDetail();
if (user.Name != null)
{
var count = UnitoffWork.UserRepository.GetAll().Where(a => a.Id == user.Id).Count();
if (count != 0)
{
objUser.Id = user.Id;
objUser.Name = user.Name.ToString();
objUser.Address = user.Address.ToString();
objUser.City = user.City.ToString();
UnitoffWork.UserRepository.Update(objUser);
UnitoffWork.UserRepository.Save();
}
}
return RedirectToAction("Index");
}
[HttpGet]
public ActionResult Delete(int Id)
{
UserDetail objUser = new UserDetail();
var user = UnitoffWork.UserRepository.GetSingle(c => c.Id == Id);
if (user != null)
{
objUser.Id = user.Id;
UnitoffWork.UserRepository.Delete(objUser);
UnitoffWork.UserRepository.Save();
}
return RedirectToAction("Index");
}
}
}
Create an Index View for the Index action method.
@model IEnumerable<CRUD_Using_Repository_Pattern.ViewModel.IndexViewModel>
@{
Layout = null;
}
<a href="@Url.Action("Add", "Home")" style="margin-left:12%" id="addNew">Add New</a>
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<table style="border: 1px solid; width: 60%; margin-left:20%">
<thead>
<tr>
<th width="30%" style="text-align:center">Name</th>
<th width="30%" style="text-align:center">Address</th>
<th width="30%" style="text-align:center">City</th>
<th width="15%" style="text-align:center">Action</th>
<th width="15%" style="text-align:center">Action</th>
</tr>
</thead>
<tbody style="border:1px solid;">
@if (Model != null)
{
foreach (var item in Model)
{
<tr>
<td style="text-align:center">
@item.Name
</td>
<td style="text-align:center">
@item.Address
</td>
<td style="text-align:center">
@item.City
</td>
<td>
<a href="@Url.Action("Edit", "Home", new { Id = item.Id })" onclick="">Edit</a>
</td>
<td>
<a href="@Url.Action("Delete", "Home", new { Id = item.Id })" onclick="">Delete</a>
</td>
</tr>
}
}
</tbody>
</table>
</div>
</body>
</html>
Create Partial View _Add for the Add action method.
@model CRUD_Using_Repository_Pattern.ViewModel.IndexViewModel
@using (Html.BeginForm("Create", "Home", FormMethod.Post))
{
<div style="margin-left:15%">
<div>
@Html.LabelFor(model => model.Name)
@Html.EditorFor(model => model.Name)
</div>
<br />
<div>
@Html.LabelFor(model => model.Address)
@Html.EditorFor(model => model.Address)
</div>
<br />
<div>
@Html.LabelFor(model => model.City)
@Html.EditorFor(model => model.City)
</div>
<br />
<input type="submit" value="Add" />
</div>
}
Create Partial View _Edit for Edit Action as.
@model CRUD_Using_Repository_Pattern.ViewModel.IndexViewModel
@using (Html.BeginForm("Update", "Home", FormMethod.Post))
{
<div style="margin-left:15%">
<div>
@Html.LabelFor(model => model.Id)
@Html.TextBoxFor(model => model.Id, new { @readonly = "readonly" })
</div>
<br />
<div>
@Html.LabelFor(model => model.Name)
@Html.EditorFor(model => model.Name)
</div>
<br />
<div>
@Html.LabelFor(model => model.Address)
@Html.EditorFor(model => model.Address)
</div>
<br />
<div>
@Html.LabelFor(model => model.City)
@Html.EditorFor(model => model.City)
</div>
<br />
<input type="submit" value="Update" />
</div>
}
Now, if we run the application, you will see the list of all users.
Now, click on Add New to add a new record.
After adding a new record, click on edit of Jeetendra to update the 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 understand CRUD operations using the Repository Pattern UnitOfWork.