Serving Industries Worldwide

Innovative Ways - Satisfied Clientele

How to perform Repository pattern in ASP.NET MVC?


Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

 
 

asp-dot-net-mvc

Table of Content

What is a Repository pattern?

The Repository pattern is the most popular pattern for creating an enterprise level application. The repository is used to create an abstraction layer between the data access layer and the business logic layer of an application.Implementation of repository patterns can help to abstract your application from changes in the data store and can facilitate automated unit testing.

Repository directly communicates with Database (Data Access Layer (DAL)) andfetch the data and provide it to the logical layer (Business logic layer (BAL)). The purpose of the Repository is to isolate the data access layer (DAL) and the Business Logic Layer (BAL). Instead of writing entire data access logic in a controller write this logic in a different class known as a repository. This will make your code maintainable and understandable.

If an application doesn't follow the repository pattern then an application has the following problems:

  1. The application has a duplicate database code.
  2. For testing database operation and business logic User Interface (UI) required.
  3. For unit test business logic external dependencies are needed.
  4. Implementation of database caching is difficult.

Using the Repository pattern has the following advantages:

  1. Database access logic is centrally managed and can be reused.
  2. Business entities strongly type.
  3. The repository pattern implements an isolation layer for data access logic and can be unit tested without data access logic.

Why the repository pattern is used?

The main purpose of the repository pattern is to isolate the data access layer and business logic.In Asp.Net MVC model is used to interact with the Data Access layer and Controller for performing Data access operation. The controller is responsible for passing data to the view. If the controller has tightly coupled to mode then any model changes directly impact on the controller and also on View.

   

How to use a repository pattern in ASP.NET MVC?

The following diagram gives an overview of the repository pattern:

process_flow_diagram

1.1-Process Flow Diagram
  1. Client business logic (IIS/web server) Request controller for read and write operations.
  2. The controller interacts with the repository to load the model based on the call.
  3. The controller uses Dependency Injection to call the repository method.
  4. Repository Interact with Database using Dbcontext and return the model to the controller.

How to use a repository pattern in ASP.NET MVC?

Step 1: Create web application

Open Visual Studio

Create new project

  1. File->New->Project->web->Asp.Net web Application (.Net framework)

Provide name and Location and Click on next.

Select the Basic template (MVC) and Click on ok.

 

Step 2: Create a table

Open Microsoft SQL server management studio.

Select the Database and Create a table.

Picture1_establish

1.2 student table
 

Step 3: Connect with the database with (Db First Approach).

Open solution explorer and Add new Data Model.

  1. Add->New Item->Data->Ado.net Data Entity Model.

Connect with the database and add a table.

  1. EF Designer from database->Add properties->Select table->Connect

Picture1_establish

1.3 Establish Connection for SQL server.
 

Step 4: Create a Repository for Employee

Create Repository folder inside the project

  1. Create a Repository and Interface inside the Repository folder.

IStudentRepository.cs

usingSystem.Collections.Generic;

namespaceRepository.Models
{
	publicinterfaceIStudentRepository
    {
		IEnumerableGetStudents();
        student GetStudentById(ints_id);
		voidInsertStudent(student s);
		voidUpdateStudent(student s);
		voidDeleteStudent(ints_id);
		voidsave();
    }
}

StudentRepository.cs

StudentRepositoryimplementsIStudentRepository

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;

namespaceRepository.Models
{
publicclassStudentRepository :IStudentRepository
    {
	private demoEntities2 _context;

		publicStudentRepository(demoEntities2 context)
		{
			this._context = context;
		}

	publicIEnumerableGetStudents()
		{
			return _context.students.ToList();
		}

	public student GetStudentById(ints_id)
		{
			return _context.students.Find(s_id);
		}
	publicvoidInsertStudent(student s)
		{
			_context.students.Add(s);
		}

	publicvoidUpdateStudent(student s)
		{
			_context.Entry(s).State = System.Data.Entity.EntityState.Modified;
		}
	publicvoidDeleteStudent(ints_id)
		{
			student s = _context.students.Find(s_id);
			_context.students.Remove(s);
		}

	publicvoidsave()
		{
			_context.SaveChanges();
		}
	publicvoidDispose()
		{
			thrownewNotImplementedException()
		}

    }

}

Step 5: Call Repository from Controller.

Add new controller

  1. Add->new Item->Controller->MVC5-Controller Empty

Controller Interact with StudentRepository by creating Reference of IStudentRepository

StudentController.cs

usingDemo.Models;
usingSystem.Linq;
usingSystem.Web.Mvc;

namespaceDemo.Controllers
{
	publicclassStudentController : Controller
		{
	// GET: Student
		privateIStudentRepositoryinterfaceobj;

		publicStudentController()
		{
			this.interfaceobj = newStudentRepository(new demoEntities2());
		}

		// GET: Student
		publicActionResultIndex()
		{
			var data = from m ininterfaceobj.GetStudents() select m;


			return View(data);
		}
		publicActionResultDetailStudent(int id)
		{
			student s = interfaceobj.GetStudentById(id);
			return View(s);
		}
		publicActionResultCreateStudent()
		{
			returnView();
		}
		[HttpPost]
		publicActionResultCreateStudent(student s)
		{
			interfaceobj.InsertStudent(s);
			interfaceobj.save();
			returnRedirectToAction("Index");
		}
		publicActionResultUpdateStudent(int id)
		{
			student s = interfaceobj.GetStudentById(id);
			return View(s);
		}
		[HttpPost]
		publicActionResultUpdateStudent(int id, student s)
		{
			interfaceobj.UpdateStudent(s);
			interfaceobj.save();
			returnRedirectToAction("Index");
		}
		publicActionResultDeleteStudent(int id)
		{
			student s = interfaceobj.GetStudentById(id);
			return View(s);
		}
		[HttpPost]
		publicActionResultDeleteStudent(int id, student s)
		{
			interfaceobj.DeleteStudent(id);
			interfaceobj.save();
			returnRedirectToAction("Index");
		}


    }
}


 

Planning to Hire an ASP.Net Web Development Company ?

Your Search ends here.


Step 6: Add View

Add View for Index, CreateStudent, DetailStudent, DeleteStudent

Index.cs

<xmp>
@model IEnumerable<Demo.Models.student>

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
@Html.ActionLink("Create New", "CreateStudent")
</p>
<tableclass="table">
<tr>
<th>
@Html.DisplayNameFor(model =>model.s_id)
</th>
<th>
@Html.DisplayNameFor(model =>model.s_name)
</th>
<th>
@Html.DisplayNameFor(model =>model.s_lastname)
</th>
<th>
@Html.DisplayNameFor(model =>model.s_bday)
</th>
<th></th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem =>item.s_id)
</td>
<td>
@Html.DisplayFor(modelItem =>item.s_name)
</td>
<td>
@Html.DisplayFor(modelItem =>item.s_lastname)
</td>
<td>
@Html.DisplayFor(modelItem =>item.s_bday)
</td>
<td>
@Html.ActionLink("Edit", "UpdateStudent", new{  id=item.s_id  }) |
@Html.ActionLink("Details", "DetailStudent", new{  id=item.s_id  }) |
@Html.ActionLink("Delete", "DeleteStudent", new{  id=item.s_id })
</td>
</tr>
}

</table>

</xmp>

CreateStudent.cs

@model Demo.Models.student @{ ViewBag.Title = "CreateStudent"; }

CreateStudent

@using (Html.BeginForm()) { @Html.AntiForgeryToken()

student


@model Demo.Models.student

@{
ViewBag.Title = "CreateStudent";
}

<h2>CreateStudent</h2>

@using (Html.BeginForm()) 
{
@Html.AntiForgeryToken()

<divclass="form-horizontal">
<h4>student</h4>
<hr/>
<divclass="form-group">
@Html.LabelFor(model =>model.s_name, htmlAttributes: new { @class = "control-label col-md-2" })
<divclass="col-md-10">
@Html.EditorFor(model =>model.s_name, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>

<divclass="form-group">
@Html.LabelFor(model =>model.s_lastname, htmlAttributes: new { @class = "control-label col-md-2" })
<divclass="col-md-10">
@Html.EditorFor(model =>model.s_lastname, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>

<divclass="form-group">
@Html.LabelFor(model =>model.s_bday, htmlAttributes: new { @class = "control-label col-md-2" })
<divclass="col-md-10">
@Html.EditorFor(model =>model.s_bday, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>

<divclass="form-group">
<divclass="col-md-offset-2 col-md-10">
<inputtype="submit"value="Create"class="btnbtn-default"/>
</div>
</div>
</div>
}

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

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}

Note: Asp.net MVC provide Template [List, add, edit, delete] for View. For adding View Right Click on the method and Add View. Select Template and add Model class.

In RouteConfig.cs file change the name of controller [Home->Student]


Step 7: Build and Run Project

Build and Run the application.

Picture_student_view_page

1.4 Student View page

Picture_student_add_page

1.5 Student Add page

Conclusion:

A repository pattern is a popular pattern for creating a web application. Repository pattern isolates Data-access Layer and Business Logic layer. So, users can easily manage Business logic without worrying about the database. By implementing repository users can unit testtheir application.

asp-dot-net-mvc

Table of Content

What is a Repository pattern?

The Repository pattern is the most popular pattern for creating an enterprise level application. The repository is used to create an abstraction layer between the data access layer and the business logic layer of an application.Implementation of repository patterns can help to abstract your application from changes in the data store and can facilitate automated unit testing.

Repository directly communicates with Database (Data Access Layer (DAL)) andfetch the data and provide it to the logical layer (Business logic layer (BAL)). The purpose of the Repository is to isolate the data access layer (DAL) and the Business Logic Layer (BAL). Instead of writing entire data access logic in a controller write this logic in a different class known as a repository. This will make your code maintainable and understandable.

If an application doesn't follow the repository pattern then an application has the following problems:

  1. The application has a duplicate database code.
  2. For testing database operation and business logic User Interface (UI) required.
  3. For unit test business logic external dependencies are needed.
  4. Implementation of database caching is difficult.

Using the Repository pattern has the following advantages:

  1. Database access logic is centrally managed and can be reused.
  2. Business entities strongly type.
  3. The repository pattern implements an isolation layer for data access logic and can be unit tested without data access logic.

Why the repository pattern is used?

The main purpose of the repository pattern is to isolate the data access layer and business logic.In Asp.Net MVC model is used to interact with the Data Access layer and Controller for performing Data access operation. The controller is responsible for passing data to the view. If the controller has tightly coupled to mode then any model changes directly impact on the controller and also on View.

   

How to use a repository pattern in ASP.NET MVC?

The following diagram gives an overview of the repository pattern:

process_flow_diagram

1.1-Process Flow Diagram
  1. Client business logic (IIS/web server) Request controller for read and write operations.
  2. The controller interacts with the repository to load the model based on the call.
  3. The controller uses Dependency Injection to call the repository method.
  4. Repository Interact with Database using Dbcontext and return the model to the controller.

How to use a repository pattern in ASP.NET MVC?

Step 1: Create web application

Open Visual Studio

Create new project

  1. File->New->Project->web->Asp.Net web Application (.Net framework)

Provide name and Location and Click on next.

Select the Basic template (MVC) and Click on ok.

 

Step 2: Create a table

Open Microsoft SQL server management studio.

Select the Database and Create a table.

Picture1_establish

1.2 student table
 

Step 3: Connect with the database with (Db First Approach).

Open solution explorer and Add new Data Model.

  1. Add->New Item->Data->Ado.net Data Entity Model.

Connect with the database and add a table.

  1. EF Designer from database->Add properties->Select table->Connect

Picture1_establish

1.3 Establish Connection for SQL server.
 

Step 4: Create a Repository for Employee

Create Repository folder inside the project

  1. Create a Repository and Interface inside the Repository folder.

IStudentRepository.cs

usingSystem.Collections.Generic;

namespaceRepository.Models
{
	publicinterfaceIStudentRepository
    {
		IEnumerableGetStudents();
        student GetStudentById(ints_id);
		voidInsertStudent(student s);
		voidUpdateStudent(student s);
		voidDeleteStudent(ints_id);
		voidsave();
    }
}

StudentRepository.cs

StudentRepositoryimplementsIStudentRepository

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;

namespaceRepository.Models
{
publicclassStudentRepository :IStudentRepository
    {
	private demoEntities2 _context;

		publicStudentRepository(demoEntities2 context)
		{
			this._context = context;
		}

	publicIEnumerableGetStudents()
		{
			return _context.students.ToList();
		}

	public student GetStudentById(ints_id)
		{
			return _context.students.Find(s_id);
		}
	publicvoidInsertStudent(student s)
		{
			_context.students.Add(s);
		}

	publicvoidUpdateStudent(student s)
		{
			_context.Entry(s).State = System.Data.Entity.EntityState.Modified;
		}
	publicvoidDeleteStudent(ints_id)
		{
			student s = _context.students.Find(s_id);
			_context.students.Remove(s);
		}

	publicvoidsave()
		{
			_context.SaveChanges();
		}
	publicvoidDispose()
		{
			thrownewNotImplementedException()
		}

    }

}

Step 5: Call Repository from Controller.

Add new controller

  1. Add->new Item->Controller->MVC5-Controller Empty

Controller Interact with StudentRepository by creating Reference of IStudentRepository

StudentController.cs

usingDemo.Models;
usingSystem.Linq;
usingSystem.Web.Mvc;

namespaceDemo.Controllers
{
	publicclassStudentController : Controller
		{
	// GET: Student
		privateIStudentRepositoryinterfaceobj;

		publicStudentController()
		{
			this.interfaceobj = newStudentRepository(new demoEntities2());
		}

		// GET: Student
		publicActionResultIndex()
		{
			var data = from m ininterfaceobj.GetStudents() select m;


			return View(data);
		}
		publicActionResultDetailStudent(int id)
		{
			student s = interfaceobj.GetStudentById(id);
			return View(s);
		}
		publicActionResultCreateStudent()
		{
			returnView();
		}
		[HttpPost]
		publicActionResultCreateStudent(student s)
		{
			interfaceobj.InsertStudent(s);
			interfaceobj.save();
			returnRedirectToAction("Index");
		}
		publicActionResultUpdateStudent(int id)
		{
			student s = interfaceobj.GetStudentById(id);
			return View(s);
		}
		[HttpPost]
		publicActionResultUpdateStudent(int id, student s)
		{
			interfaceobj.UpdateStudent(s);
			interfaceobj.save();
			returnRedirectToAction("Index");
		}
		publicActionResultDeleteStudent(int id)
		{
			student s = interfaceobj.GetStudentById(id);
			return View(s);
		}
		[HttpPost]
		publicActionResultDeleteStudent(int id, student s)
		{
			interfaceobj.DeleteStudent(id);
			interfaceobj.save();
			returnRedirectToAction("Index");
		}


    }
}


 

Planning to Hire an ASP.Net Web Development Company ?

Your Search ends here.


Step 6: Add View

Add View for Index, CreateStudent, DetailStudent, DeleteStudent

Index.cs

<xmp>
@model IEnumerable<Demo.Models.student>

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
@Html.ActionLink("Create New", "CreateStudent")
</p>
<tableclass="table">
<tr>
<th>
@Html.DisplayNameFor(model =>model.s_id)
</th>
<th>
@Html.DisplayNameFor(model =>model.s_name)
</th>
<th>
@Html.DisplayNameFor(model =>model.s_lastname)
</th>
<th>
@Html.DisplayNameFor(model =>model.s_bday)
</th>
<th></th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem =>item.s_id)
</td>
<td>
@Html.DisplayFor(modelItem =>item.s_name)
</td>
<td>
@Html.DisplayFor(modelItem =>item.s_lastname)
</td>
<td>
@Html.DisplayFor(modelItem =>item.s_bday)
</td>
<td>
@Html.ActionLink("Edit", "UpdateStudent", new{  id=item.s_id  }) |
@Html.ActionLink("Details", "DetailStudent", new{  id=item.s_id  }) |
@Html.ActionLink("Delete", "DeleteStudent", new{  id=item.s_id })
</td>
</tr>
}

</table>

</xmp>

CreateStudent.cs

@model Demo.Models.student @{ ViewBag.Title = "CreateStudent"; }

CreateStudent

@using (Html.BeginForm()) { @Html.AntiForgeryToken()

student


@model Demo.Models.student

@{
ViewBag.Title = "CreateStudent";
}

<h2>CreateStudent</h2>

@using (Html.BeginForm()) 
{
@Html.AntiForgeryToken()

<divclass="form-horizontal">
<h4>student</h4>
<hr/>
<divclass="form-group">
@Html.LabelFor(model =>model.s_name, htmlAttributes: new { @class = "control-label col-md-2" })
<divclass="col-md-10">
@Html.EditorFor(model =>model.s_name, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>

<divclass="form-group">
@Html.LabelFor(model =>model.s_lastname, htmlAttributes: new { @class = "control-label col-md-2" })
<divclass="col-md-10">
@Html.EditorFor(model =>model.s_lastname, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>

<divclass="form-group">
@Html.LabelFor(model =>model.s_bday, htmlAttributes: new { @class = "control-label col-md-2" })
<divclass="col-md-10">
@Html.EditorFor(model =>model.s_bday, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>

<divclass="form-group">
<divclass="col-md-offset-2 col-md-10">
<inputtype="submit"value="Create"class="btnbtn-default"/>
</div>
</div>
</div>
}

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

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}

Note: Asp.net MVC provide Template [List, add, edit, delete] for View. For adding View Right Click on the method and Add View. Select Template and add Model class.

In RouteConfig.cs file change the name of controller [Home->Student]


Step 7: Build and Run Project

Build and Run the application.

Picture_student_view_page

1.4 Student View page

Picture_student_add_page

1.5 Student Add page

Conclusion:

A repository pattern is a popular pattern for creating a web application. Repository pattern isolates Data-access Layer and Business Logic layer. So, users can easily manage Business logic without worrying about the database. By implementing repository users can unit testtheir application.