ASP.Net MVC with Entity Framework and Repository Pattern

Repository pattern provides more object oriented way of encapsulating objects of the data store and operations can performed through neatly separated data classes. Please find below how Repository pattern implemented with entity framework and is consumed using asp.net mvc. Use either StructureMap or Ninject for dependency injection of the Entity Repository Factory object to the Controller classes.

Let us look at the Solution Structure first,

clip_image002

Inside the Models, there is two folders DataInterfaces and Data. DataInterfaces folder contains Repository Interfaces and Data folder contains the Operating classes.Created NorthwindEntities using entity framework with Northwind Database.

Class Diagram of Repository

clip_image004

IBaseRepository

Defines the interfaces that has the generic functionalities, which is need to be implemented in all repositories.

image

IRepositoryFactory

Factory interface for the repositories, defines the interfaces to access the data objects, in this case customer object.

clip_image008

ICustomerRepository

Entity specific repository, this is how the behavior of the object can be extended and can implement specific methods for the particular object.

clip_image010

AbstractEntityRepository

This abstract class implements the Base interface method for all repositories.

clip_image012

EntityRepositoryFactory

Entity repository Factory class, through the data objects are exposed.

clip_image014

CustomerRepository

Data object classes implements the object repository, in this case ICustomerRepository.

clip_image016

EntityManager

Provides the shared instance of the Entity Framework.Implemented using singleton pattern with nested class.

image

CustomerController

Before the controller implementation, run the test through the CustomercontrollerTest class.

Please see below, how this is implemented in the controller class. Using either StructureMap or Ninject for dependency injection of the Entity Repository Factory object to the Controller class.And refer the related entity i.e. Customer Entity in this case using GetCustomerEntity() and call required method.

image

This completes implementation of sample method, Now ready to run the application. See the results below. Improved the look and feel using design template from http://www.ASP.net/mvc/gallery.

image

 image