Published: 16 May 2012
By: Akhil Mittal
Download Sample Code

A detailed introduction about the code first approach using Entity Framework 4.1, Inversion of Control, Unity Framework, Repository and Unit of Work Patterns, and MVC3 Razor View.

Contents [hide]


In my previous article I discussed about developing a simple basic multilayered architecture for a .Net application. However there were few points that I skipped considering that the article was for beginners. When we talk about application architecture there are certain points that need to be put into consideration before initiating:

  • Is the architecture loosely coupled?
  • Is it to be service based?
  • Where should the entities reside?
  • What should be Mode of Communication with the database?
  • Does it require design patterns? If yes, what patterns should be implemented?
  • Should it be based on Separation of Concerns?

To answer these type of questions, .Net 4 has come up with a generic solution, making use of Entity Framework.

My effort in this article would be to put some light on building a generic multilayered architecture using Entity Framework 4.1 and MVC3 razor view engine. We'll use inversion of control to resolve dependency of layers. The points to be covered in this article would be as follows

  • Use of Separation of Concerns,
  • Use of Code First approach,
  • POCO objects,
  • Repository Pattern,
  • Dependency Injection and Inversion of Control.

Architecture Overview

I have created an architecture to explain all the above mentioned points, and we'll stick to this architecture till the end of article thus implementing practically our understanding.

I have created a very simple application to add student details in database, to edit it and to delete it. My first page shows a list of all added student. The architecture is service based, following are the components and pictorial representation (fig1) of it, we'll discuss each component in detail.

  • CodeFirstData layer.
  • CodeFirstEntities layer.
  • CodeFirstServices layer.
  • MVC Portal layer.

Architecture components

Let's discuss each and every component of the defined architecture in detail.

CodeFirstData layer

The data layer is the class library defining a layer which is responsible for interacting with database, contains context classes and a factory pattern implementation to interact with database. The layer contains the repository for each entity to map with database, thus making a complete ORM (Object Resource Model) solution. The class library references EntityFramework dll to implement the dbcontext classes.

CodeFirstEntities layer

Entity layer acts as a model to MVC application, and is also responsible for the creation of DataBase objects when the dbset is first executed. It contains Entity classes in POCO form, having relations and data annotations(Rules/Constraints to be put on Database table/columns).

The properties of the class results in column name in database and name of the class in Dtaabase table. Primary key is either defined by the property named Id or Classname[Id], in our case StudentId is default protocol set by entity framework to keep in mind while creating entities. Since this application is codefirest, we need to create entities first.

CodeFirstServices layer

The layer contains services which uses repositories to fetch data from database. The interaction between Services and Repositories is kept loosely coupled thus implementing Inversion of Control using Dependency Injection. Its constructor based dependency injection does not allow service to make direct instance of our repositories. Service layer acts as an interface between controllers and repositories, passes request of controller to repositories.

MVCPortal layer

MVCPortal layer is our UI layer; it contains Model/ViewModels, Views and Controllers. I am not going into details of MVC as it's not our primary target. I assume that you already know how to create and run MVC application. Let's have a quick revision of MVC,

Model / Viewmodel

Model classes are responsible for holding up and manipulating data. We bind model/viewmodel classes to views to display model specific data. Model classes are prepopulated by controllers to show data with the help of views.


Views hold up our UI templates. We have controller methods defined for every view, which populates View Design with data, and requests particular type of view to be rendered at user's end as per requirement.


Web-based MVC frameworks map URLs to server code in a bit different fashion. Instead of mapping incoming URLs to html/aspx files, they instead map URLs to methods on classes. These classes are called "Controllers" and they are responsible for processing incoming HTTP requests, handling user input, retrieving and saving data, and determining the response to send back to the client (display HTML, download a file, redirect to a different URL, etc.).

The layer makes use of Dependency injection to achieve Inversion of Control for services, thus not allowing controllers to directly access services instances. The IOC is achieved using global.asax file using the UnityFramework library of Microsoft.


I have created DLLs folder and given the output build path for every class library to that folder, for ease of access to dll's to add reference.Now each dll will be created in the dlls folder and we can access the desired dll from the same folder. Also keep the EntityFramework, UnityConfiguration dlls into it.

IOC and DI

Dependency Injection is an important component in my application. All the services are required to be late bound with Model layer with Dependency Injection. In addition, the IoC container manages the lifetime of service objects. For example the Context object. I set lifetime type as PerThreadLifetimeManager in Unity configuration. This makes one and only one context object created in a single request and the different request has a different context object. Another thing I want to mention is ASP.NET MVC3 has its own way to provide Dependency Inject for controller via implementing DependencyResolver interface. The IoC container I used in the demo is Unity.


The "Container" or "IOC Container" is the main object that is used to create objects and inject dependencies into them. Whenever you want an object to be open to IoC, you have to use the container to create the instance using container.Resolve<T>() method instead of the "new" keyword.

I have added following references to achieve the same:

The code for IOC is implemented in global.asax file.

Application Overview

We'll try to develop a simple studentDetails application with the help of discusses architecture. The application's main module will be to Create a new student, Edit existing student, Delete existing student, and to show list of all students. Looking into a wider/generic perspective, the application performs CRUD operations on database with the help of EF.

Note that we'll not create database by our own. We just write classes and defining connection configuration of our database server in web.config file, and let Entity Framework do rest of the job of creating database, managing database and Mapping database with our entities.

Step1. Creating a solution and blank projects/seperating them logically/physically as layers

Our first initiative is to prepare our initial level architecture there by creating solution and adding project files to it, We create a solution named CodeFirstEntities and add three class libraries to it thus defining our three layers which are Entity, Data and Service, the names of the class libraries which i chose are CodeFirstEntities, CodeFirstData and CodeFirstServices respectively.

Now add an MVC3 application to the solution called MvcPortal, which will act as a UI layer for our application. Refer fig2 for implementing the first step.

Step 2. Creating Entities

Add Student.cs class to CodeFirstEntities project, this class will contain the student details specific properties that will take the shape of database table and columns . The class makes use of DataAnnotation dll to put data annotations (rules/constraints) over the properties that will be reflected in database table. The constraints like max length and required parameter are provided as attributes over the properties of the class as shown in fig3 and fig4,

The above entities is very simple POCO (Plain Old CLR Object) class and the entity Student is decorated with validation attributes in the System.ComponentModel.DataAnnotations namespace. Now we want to use these entities for defining model objects for the Entity Framework 4. Using the Code First approach of Entity Framework, we can first define the entities by simply writing POCO classes without any coupling with any API or database library. This approach lets you focus on domain model which will enable Domain-Driven Development for applications. EF code first support is currently enabled with a separate API that is runs on top of the Entity Framework 4.

Step 3. Creating Repositories/Contexts

Our next step is to create the contexts/repositories for our application and classes that will interact with the database.

We have already prepared our domain model now let's create a class in order to working with Entity Framework Code First. I have added reference to EntitFramework.dll CTP 4.1 to this class library project. We create two folders DBInteractions and EntityRepositories to segregate our classes as in fig5, we'll come to that later, first let me explain you the context class.

The above class CodeFirstContext in fig 6 is derived from DbContext that can connect your model classes to a database. The CodeFirstContext class is mapping our Student class to database tables Student use DbSet<TEntity> where TEntity is any POCO class. When we are running the application at first time, it will automatically create the database. EF code-first look for a connection string in web.config or app.config that has the same name as the dbcontext class. If it is not find any connection string with the convention, it will automatically create database in local SQL Express database by default and the name of the database will be same name as the dbcontext class. You can also define the name of database in constructor of the the dbcontext class. The model classes of Code First are working on the basis of conventions and we can also use a fluent API to refine our model. The convention for primary key is 'Id' or '<classname>Id' as I discussed before. If primary key properties are detected with type 'int', 'long' or 'short', they will automatically registered as identity columns in the database by default. Primary key detection is not case sensitive. We can define our model classes with validation attributes in the System.ComponentModel.DataAnnotations namespace and it automatically enforces validation rules when a model object is updated or saved.


We have now created model class and dbcontext class. Now we create a generic repository pattern for data persistence with EF code first. Let's create a generic repository to working with DbContext and DbSet as follows. The following classes will be added to DBInteractions folder for ease of understanding logic.

DataBase Factory

We have our database factory class defined as follows:

Where IDBFactory is the interface implemented by our factory class DBFactory. The factory class is inherited from Disposable class as shown below in fig 10, responsible for releasing disposing database resources.

RepositoryBase – The Generic Entity Repository base class

Above is the repository base class that contains all the methods to be implemented for CRUD DB operations, we can define more of our generic methods here, for now considering our application, these are eough for proper understanding of the working.

E. Unit of Work

The Unit of Work pattern maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems. We create a class for handling Unit of Work pattern.



The Commit method written in of the UnitOfWork will call the commit method of our Context class and it will execute the SaveChanges method of DbContext class.


In this article, we will primarily focus on the persistence against Student entity . Let's create a repository for handling CRUD operations for Student by deriving from a generic Repository EntityRepositoryBase<T>.



Creating a Service layer

Service Layer defines an application's scope and its available set of operations from the perspective of interfacing client layers. It encapsulates the application's business logic, controlling transactions and coordinating responses in the implementation of its operations. Controller classes should be made light and do not put much of business logic onto it. We can use the service layer as the business logic layer and can encapsulate the rules of the application.

We define interfaces and corresponding student service for our application business logic. Since we are targeting CRUD operations, the methods are quite simple to implement.


As we can see in above interface the methods are to Get Student Details, List, Update and DeleteStudent.

Listing 1: Class

Class uses references to Repositories and Entities, and Dependency of Repositories is resolved in Constructor of the service itself.

The MVC Portal

Before we start the MVC portal, let's clear our logic for IOC and DI.I have already discussed IOC in the article. For resolving Dependency we create certain classes as discussed below, to get independent service request. We also create a custom lifetime manager for Unity to store container in the current HttpContext.

We create a dependency resolver for resolving service dependency as follows. ASP.NET MVC 3 has introduced a new interface IControllerActivator which lets you activate controllers with custom behavior and can be use it for dependency injection purpose. The IControllerActivator interface is discoverable using the dependency resolver. Let's create a custom controller activator class by deriving from IControllerActivator interface.

We also create a UnityController Factory and Configure contract and concrete types of unity in global.asax file. ASP.NET MVC 3 has also introduced a new interface IDependencyResolver which exposes two methods - GetService and GetServices. The GetService method resolves singly registered services that support arbitrary object creation and the GetServices method resolves multiply registered services. Implementations of the IDependencyResolver interface should delegate to the underlying dependency injection container to provide the registered service for the requested type. When there are no registered services of the requested type, the ASP.NET MVC framework expects implementations of this interface to return null from GetService and to return an empty collection from GetServices. Let's create a custom dependency resolver class by deriving from IDependencyResolver intreface in order to working with Unity to providing dependency injection.

Listing 2: Resolving Service Dependency


Add service project reference , entity project reference and data project reference to the portal. The SetResolver method of DependencyResolver class provides a registration point for dependency injection containers. In this method, we configure the UnityDependencyResolver class for providing dependency injection with Unity 2.0. The SetResolver method will be working with any dependency injection container. If you want to use StructureMap as the dependency injection container, you can create a dependency resolver class in order to working with StructureMap by deriving IDependencyResolver intreface and later you can configure this class with SetResolver method. The ASP.NET MVC 3 is providing a good support for working with dependency injection containers.

To Start with MVC our first step is to define our connection string as follows in the web.config file.

Steps to Create Controllers and Views

We start with home Controller, as it is the default controller set in global.asax to be called first.

When the Index action of the controller is called we redirect it to our Student Controller, which straight away returns view to show lists of students if exist, since its first time we are creating the controller, it shows an empty list, the controller method of Student fetches student list from database , but first it creates the database, thus achieving our objective.

We create Student Controller; we define actions in the controller for each operation we want to perform as follows.

There are get and corresponding Posts for each method responsible for Data Updations. The Constructor of the controller initializes the Service, we can see it do not create direct instance.

We Create Views for every Action. It's easy if we right click the controller action and create view, it automatically create a view with a Default folder named in the name of Constructor, so we can create all the views for our operations, and our solution looks like the figure below.

Now we are ready with our application to be executed. Keep your fingers crossed and see the magic, I have used _layout as master page to give some meaningful look and feel to my application. You can customize the same. When you run the application by pressing F5, we get redirected to the Index view of Student Controller, which shows list of students. Since we are running it first time, we don't have any existing list, and our application shows the following response:

Have a look at your DataBase. I'm using Sql Server 2008.

I got a Database created automatically with the name CodeFirstApp having Student Table. Now you can cross verify that the table with your entity is the same. So we have hit the target and our database is successfully created.

Further Operations

You can now test the application and perform further CRUD operations in the application and see the DataBase getting updated.

After submitting the form by pressing Create, we get the following response:

We can edit the same student by pressing edit link, we get the following view.

Likewise we can see the details of already created student.

And deleting the student will redirect to the following page.

I had created 3 students in the same manner. You can create more and play with the application.

Risk Factor

There is also a Risk Factor in implementing EntityFramework, if we do any change in the entity, like deleting, changing property, the context will drop and recreate the database, which may clearly lead to loss of your existing data. To avoid this critical situation, we code some more, we call the SetInitializer method of database class and set it to null in our database Factory Class.

The Database class is from namespace System.Data.Entity, which provides such feature.


In this article we discussed about creating an application using EntityFramework 4.1 Code First Approach, We used Inversion of control and Dependency Injection to Resolve Dependency between layers. We used MVC 3 razor view engine as our UI and integrated the layers to achieve our objective. The application was a description of simple CRUD operations on Database. We learned how to use Repository Pattern, Unit of Work pattern and Unity Framework. You can download the codebase and further enhance/extend it according to your need.

Happy Coding.

<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About Akhil Mittal

I currently work as an Engineer Analyst in anMNC and have an experience of about 5 years in C#.Net. I am a B.Tech in Computer Science and hold a diploma in Information Security and Application Development. My work experience includes Development of Enterprise Applications using C#,.Net and Sql Serve...

This author has published 4 articles on DotNetSlackers. View other articles or the complete profile here.

Other articles in this category

Exception Handling and .Net (A practical approach)
Error Handling has always been crucial for an application in a number of ways. It may affect the exe...
jQuery Mobile ListView
In this article, we're going to look at what JQuery Mobile uses to represent lists, and how capable ...
Book Review: SignalR: Real-time Application Development
A book review of SignalR by Simone.
JQuery Mobile Widgets Overview
An overview of widgets in jQuery Mobile.
jQuery Mobile Pages
Brian Mains explains how to create pages with the jQuery Mobile framework.

You might also be interested in the following related blog posts

Business Apps Example for Silverlight 3 RTM and .NET RIA Services July Update: Part 25: ViewModel read more
Going Controller-less in MVC: The Way Fowler Meant It To Be read more
ViewData mechanics and segmentation (excerpt from ASP.NET MVC in Action) read more
Simplicity is key to successful unit testing - Part 2 read more
Implement Master-Detail layout with ASP.NET MVC read more
Delegating Decorators read more
ASP.NET MVC Preview 3 Release read more
Introducing the SmartBag for ASP.NET MVC. . . and soliciting feedback read more
ASP.Net Framework - Create your own RouteHandler read more
The New ASP.NET Framework read more


Subject Author Date
placeholder CodeBase P T 5/17/2012 4:17 AM
RE: CodeBase Akhil Mittal 5/21/2012 1:13 AM
placeholder Quite easy to understood and implement. Udeep Kansal 5/28/2012 1:20 AM
Great article!! Tim 88 7/29/2012 4:41 PM
placeholder Thanks Akhil Mittal 7/30/2012 12:08 AM
Code Review Nishant Chaturvedi 2/19/2013 3:06 PM
placeholder issue in db connection Archan Jain 7/19/2013 2:32 AM
RE: issue in db connection Akhil Mittal 7/20/2013 11:11 AM
placeholder RE: RE: issue in db connection Archan Jain 7/24/2013 1:40 AM
RE: RE: issue in db connection Akhil Mittal 7/24/2013 1:55 AM
placeholder great one!! Rajesh Gajra 8/7/2014 2:08 PM
RE: great one!! Akhil Mittal 8/8/2014 12:16 AM
placeholder Good Job Santhakumar Munuswamy 9/20/2015 10:48 AM

Please login to rate or to leave a comment.