Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC using Entity Framework

Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC using
Entity Framework

Introduction:

The repository and unit of work patterns are intended to
create an abstraction layer between the data access layer and the business
logic layer of an application. Implementing these patterns can help insulate
our application from changes in the data store and can facilitate automated unit
testing or test-driven development (TDD).

In
this article, I am implementing a repository class for Student entity type. I have created a one interface class i.e. “IStudentRepository.cs” and one
repository class i.e. “”StudentRepository.cs.
When we instantiate the repository in controller, we will use the interface so
that the controller will accept a reference to any object that implements the
repository interface. When the controller runs under a web server, it receives
a repository that works with the Entity Framework. The unit of work class
coordinates the work of multiple repositories by creating a single database
context class shared by all of them.

In
simple MVC application, we are not implementing this pattern because we do not
know about how to create an abstraction layer between data access layer and the
business logic layer of an application. Before implementing this type of
repository, we have directly connected IIS server to the controller and the controller
is a directly connected to a context file i.e. Database. We have not any layer
between them. The Repository is providing a much facility for testing, security
and divided multiple works with same context file for multiple controller, when
we created a unit of work. When we use a Repository, Repository is connected
with a controller and Unit of Work along with the database. And, its play a
centralized role for each one, so we are easily design an application. We have
also designed a generic type entity in our application that reduce the line of
code and accessible for all entity types.

Note: Here, we have a one model of Student.
I have also created view for curd operation separately (i.e.
Create,Update,Delete,Details and Index view). The Student model structure is as follows:

(Note that here, Course model is same as above Student
model curd operations. It means, using Course model, I have already created a
view for Create,Update,Delete,Details and Index. )

For creating a Unit of Work of Course model, we have need a
generic repository because we have not want to create a separate repository for
each model. So, removing this overhead we have created a GenericRepository class .(In above Course model we
have need two type of repository one for Course
and another for Department. So I have
choose creating generic repository for both to access a single context file).
Code is
as follow for GenericRepository.cs: