Introduction

ASP.NET MVC and Entity Framework is a good combination for a web application that has database backend on Microsoft platform. In this article, I will provide a demo application that is developed with the ASP.NET MVC3 and Entity Framework 4.1. The demo also adopts the following design principal, pattern and best practice to make it more flexible and extensible.

Separation of Concerns

POCO

Code-First

Registry Pattern

Repository Pattern

Persistence Ignorance

Dependency Injection

Unit Testing

In order to open and run the demo application, you need to have SQL Server/SQL Server Express with Northwind sample database and Visual Studio 2010 with ASP.NET MVC3 and Entity Framework 4.1.

Demo Application Architecture

ASP.NET MVC already has very good defined layers. In my demo, I move Model layer into its own assembly to allow reusable in other applications. Also, the model is a rich model that not just contains data and behaviors, also gets more responsibility via services. The application architecture is like this:

Design Principal, Pattern, and Best Practice

I will not go through every detail of my demo application. The source code shows the complete picture. I will only focus on those design principals, patterns, and best practices used in here.

Separation of Concerns

The ASP.NET MVC already follows Separation of Concern principal pretty good, it puts UI into View layer, interaction into Controller layer, and domain entities into Model layer. The only improvement I made in this demo application is to further moving Model layer into a separate assembly and has a Data layer to contain data access logics with Entity Framework.

POCO

I use Visual Studio 2010 Extension Manager installed ADO.NET C# POCO Entity Generator generated my original POCO domain entity Customer and Order based on Entity Data Model (edmx). The code generated is default in Data layer, I moved them from Data layer into Model layer and completely removed code generator template files. The domain entity will be enhanced and modified manually since that except there are some major table structure changes.

Code-First

Code-First in Entity Framework is different with Model-First and Database-First. Honestly, I follow the Code-First philosophy without use exact Code-First steps to setup project in the beginning. Instead, I created Entity Data Model from database, then use it to generate the original domain entity code and moved the code into model layer. So, the Code-First approach is just to allow me to isolate future domain entity code changes with database changes completely.

Registry Pattern

Model layer has a special public static object Registry that is a well-known object to let other objects using it find common objects and services. This is an implementation of Registry pattern in Pattern of Enterprise Application Architecture (PoEAA) book. In my demo application, Registry object allows domain entities and upper layers to locate Repository service - Context and RepositoryFactory.

Repository Pattern

In Hibernate application, there is a pattern called Data Access Object (DAO) pattern, the Repository Pattern is the counterpart pattern with a different name in Entity Framework. I read Repository Pattern implementation code in NerdDinner, it is not separating data access logic to its own layer good enough. In my demo, Repository Interfaces all reside in Model layer to provide data service access point, then use Dependence Injection to inject specific Data layer implementation into Model layer. The reason for this kind of implementation is to promote Model centric idea and allow switching Data layer for different implementation or Unit Test.

Persistence Ignorance

Define data access interfaces in Model layer and put Data layer into its own assembly encourage Persistence Ignorance here, Model layer and upper layers don’t really need to worry about how the model gets loaded, updated, or saved by the data layer. Additionally, I can switch Data layer to different ORM framework, like NHibernate, or a Mock implementation whenever it is necessary.

Dependency Injection

Dependency Injection plays a crucial part in my demo. All services module need to be late bound with Model layer with Dependency Injection. In addition, the IoC container manages the lifetime of service objects. One example is 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. I tried it, but eventually not adopt it because my application is Model centric application, so Registry is a better place to locate all the services instead of controller constructor. The IoC container I used in the demo is Unity. The MEF IoC container is getting more popular at the moment, but it’s more intrusive to domain entities by using attribute and not allowing configurable dependencies that make me hesitate to use it.

Unit Test

I usually use Test Project to automatically integration test instead of pure unit test. The reason I do this is to allow the test be more close to user acceptance test to avoid thinking of every possible test scenario for each single class in my application. In this demo, the CustomerControllerTest will have test case Index to test CustomerController Index action. There is another project Demo.DataMock that is the mock of Data layer. I can use mock framework (e.g. MOQ) to mock Data layer in test case, but I decide to not use it because I don’t want a permanent mock for Data layer in test case, I want Data layer mock during development and build process, on the other hand, I also want my test can run against the real data layer before I check in my changes to make sure the test case can be all passed in the “production” environment. I understand running again the real database is slow, but keep in mind, with test being more close to real usage allows me to uncover more possible bugs and the running again of real database is just a one time thing for each check in or before release to QA.

Comments and Discussions

1. Registry pattern with static properties for dependecy injection is best solution?
2. Why there are no dbset properties in context.cs class. WIthout DBSet properties with poco objects context is not working.

I am using this architecture for my project, i am facing an issue here, i have 2 ajax calls for controller method given below.

1. Ajax Call to controller method to update database, database is getting updated.
2. Ajax Call to controller method to retrieve updated values, the retrived values are still holding old values not the updated one.

As per my analysis context still holding old values, we have refreshed context too, but it doesnt work. My doubt is this because of static context property, i have my bad experieces with static variables.
Any help would be greatly appreciated.

Thank you for interesting in my article
1. The Registry pattern is used to get common objects and services, such as IoC container. Please reference to Martin Fowler's book POEAA. The static property is the easiest one I can think, but you may use getter method instead.
2. The Context class inherit the DbContext class, so it can access all public methods of DbContext. Please check the Context.cs file in Demo.Data project.

Thank you for interesting in my article. The reasons I prefer POCO are
1. POCO is implementation independent. It's not tight with Entity Framework.
2. POCO is simple and light weight, so it's a good choice for passing around between different layers.
3. POCO can be used to contain business rule. I usually like to make domain class as POCO, so it can be reused in all the places.

Please first check your web.config file to make sure you have the right class and assembly name there, and then check the bin folder of your web application to make sure Assembly files that specified in web.config exist.

This return an error only if i am passing the object throughpublic ActionResult Edit(Customer customer)

Error Message
============
"The view 'An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.' or its master was not found or no view engine supports the searched locations. The following locations were searched:
...."

but when remove the Registry part (without IoC), it works

it return an error only if i am passing the object through
public ActionResult Edit(Customer customer)

when i change it to public ActionResult Edit(int id, FormCollection collection), with tryupdate function it also works

Can you tell me how I would attach a stored procedure? I am not able to get a direct binding to the Entity object... I was trying a IStoredProcedureRepository and StoredProcedureRepository approach but I seem to cannot get it. It would be in the data project as well as the model project wouldn't it?

From my experience, the entity model is used to avoid stored procedure as much as we can, specially for Insert/Update/Delete. The reason is stored procedure contains business logic in database, but DDD (Domain-driven Design) want to contain business logic in business layer, so I don't feel any good way to handle your situation.