The MVC framework is one of the common design patterns in modern web applications. It provides a complete separation of concerns. But even MVC is not a silver bullet for all problems. On top of MVC, we can implement various design patterns to solve the specific problem.
In this example, we will first implement a sample application using pure MVC architecture and then we will see how to improve our code standards by implementing the repository design pattern. So, let's start with one example.
I will suggest you create one MVC application. Let's create the table first then we will set up the Entity Framework in the application. Here is the table structure.
![MVC application]()
We have added the Entity Framework file (.edmx) file and the model is like this.
![Framework file]()
Now let's implement a Company controller and implement CRUD operations. Have a look, we have messed up the database operations within the controller. Now if you decide to change it, how will you implement your data access layer? Right now, the Contact Manager application uses the Microsoft Entity Framework to access the database. However, you might decide to migrate to a new or alternative data access technology such as ADO.NET Data Services or NHibernate. However, because the data access code is not isolated from the controller code, there is no way to modify the data access code in your application without modifying other code that is not directly related to data access. Have a look at the following example.
Ok, we understand the problem; how to solve it? The solution is the Repository Design Pattern, we will totally isolate the DB operation part into a different class and we will consume the service (yes, let's think of the class as a service class) into our actual controller class.
For that, at first, we will create an interface and a repository for CRUD operations, and then we will implement the interface within the concrete class.
So, the following is the Interface implementation.
There are five functions within this Interface that we will implement in a class shortly. Here, we have implemented an ICompany interface within a “CompanyRepositary” class. Have a look at the following example.
Repository class for CRUD operation
We will now consume the repository service within our actual controller class. Here is the controller implementation. Now, have a look that, we have totally isolated the DB operation from our controller class. So, now the Company controller is de-coupled in nature and we have injected a dependency through the controller.
Implementation of Company repository in the controller
The great advantage of this de-coupled architecture is unit testing. If we create one mock repository class and inject it in a controller then we can avoid execution of the DB part at the time of unit testing. I am interested in implementing and showing it in my next article. So, please follow my next article here.