Formatters And Content Negotiation In ASP.NET Web API 2


Introduction

As the title suggests, this article will focus on the practical aspects of the formatters and the content negotiation in ASP.NET Web API. This article will explain what content negotiation is and why it is necessary, and how to achieve and get it working in ASP.NET Web API. The article will focus more on the implementation part of the content negotiation in Web API. The first part of the article will focus on the formatters, where it is described, how to support XML or JSON formats in Web API and how to format the result of the API. We’ll take a sample Web API project, that caters simple CRUD operations on the database, using the Entity Framework. We’ll not go into the details of underlying project architecture and the standard way of architecture of the same, but will focus on the content negotiation part in Web API projects. For creating a standard enterprise level Application with Web API, you can follow this series. You can find all the downloads related to this article at the end of the post.

Continue reading “Formatters And Content Negotiation In ASP.NET Web API 2”

Advertisements

RESTful Day #2: Inversion of control using dependency injection in Web API’s using Unity Container and Bootstrapper


Introduction

My article will explain how we can make our Web API service architecture loosely coupled and more flexible. We already learnt that how we can create a RESTful service using Asp.net Web API and Entity framework in my last article. If you remember we ended up in a solution with a design flaw, we’ll try to overcome that flaw by resolving the dependencies of dependent components. For those who have not followed my previous article, they can learn by having the sample project attached as a test application from my first article.

There are various methods you can use to resolve dependency of components. In my article I’ll explain how to resolve dependency with the help of Unity Container provided by Microsoft’s Unity Application Block.
We’ll not go into very detailed theory, for theory and understanding of DI and IOC you can follow the following links: Unity and Inversion of Control(IOC). We’ll straight away jump into practical implementation.

Roadmap

Our roadmap for learning RESTful APIs remains same,

I’ll purposely use Visual Studio 2010 and .NET Framework 4.0 because there are few implementations that are very hard to find in .NET Framework 4.0, but I’ll make it easy by showing how we can do it.

Existing Design and Problem

We already have an existing design. If you open the solution, you’ll get to see the structure as mentioned below,
The modules are dependent in a way,
There is no problem with the structure, but the way they interact to each other is really problematic. You must have noticed that we are trying to communicate with layers, making the physical objects of classes.
For e.g.
Controller constructor makes an object of Service layer to communicate,
        /// <summary>
        /// Public constructor to initialize product service instance
        /// </summary>
        public ProductController()
        {
            _productServices =new ProductServices();
        }
Service constructor, in turn, makes and object of UnitOfWork to communicate to database,
        /// <summary>
        /// Public constructor.
        /// </summary>
        public ProductServices()
        {
            _unitOfWork = new UnitOfWork();
        }
The problem lies in these code pieces. We see Controller is dependent upon instantiation of Service and Service is dependent upon UnitOfWork to get instantiated. Our Layers should not be that tightly coupled and should be dependent on each other.
The work of creating object should be assigned to someone else. Our layers should not worry about creating objects.
We’ll assign this role to a third party that will be called our container. Fortunately, Unity provides that help to us, to get rid of this dependency problem and invert the control flow by injecting dependency not by creating objects by new but through constructors or properties. There are other methods too, but I am not going into detail.

Introduction to Unity

You can have a read about Unity from this link; I am just quoting some lines,
“The Unity Application Block (Unity) is a lightweight, extensible dependency injection container that supports constructor injection, property injection, and method call injection. It provides developers with the following advantages:
  • It provides simplified object creation, especially for hierarchical object structures and dependencies, which simplifies application code.
  • It supports abstraction of requirements; this allows developers to specify dependencies at run time or in configuration and simplify management of crosscutting concerns.
  • It increases flexibility by deferring component configuration to the container.
  • It has a service location capability; this allows clients to store or cache the container. This is especially useful in ASP.NET Web applications where developers can persist the container in the ASP.NET session or application.”

Setup Unity

Open your Visual studio, I am using VS 2010, You can use VS version 2010 or above. Load the solution.
Step 1: browse to Tools-> Library Packet Manager – > Packet manager Console,
We’ll add package for Unity Application Block.
In the left bottom corner of Visual Studio, You’ll find where to write the command.
Type command Unity.MVC3 and choose “WebApi” project before you fire the command.
Step 2: Bootstrapper class
Unity.MVC3 comes with a Bootstrapper class, as soon as you run the command, the Bootstrapper class will be generated in your solution->WebAPI project,
using System.Web.Http;
using System.Web.Mvc;
using BusinessServices;
using DataModel.UnitOfWork;
using Microsoft.Practices.Unity;
using Unity.Mvc3;

namespace WebApi
{
    public static class Bootstrapper
    {
        public static void Initialise()
        {
            var container = BuildUnityContainer();

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

            // register dependency resolver for WebAPI RC
            GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
        }

        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();

            // register all your components with the container here
            // it is NOT necessary to register your controllers
            
            // e.g. container.RegisterType();        
            container.RegisterType().RegisterType(new HierarchicalLifetimeManager());

            return container;
        }
    }
}
This class comes with an initial configuration to setup your container. All the functionality is inbuilt, we only need to specify the dependencies that we need to resolve in the “BuildUnityContainer“, like it says in the commented statement,
            // register all your components with the container here
            // it is NOT necessary to register your controllers
            
            // e.g. container.RegisterType();
Step 3: Just specify the components below these commented lines that we need to resolve. In our case, it’sProductServices and UnitOfWork, so just add,
container.RegisterType().RegisterType(new HierarchicalLifetimeManager());
HierarchicalLifetimeManager” maintains the lifetime of the object and child object depends upon parent object’s lifetime.
If you don’t find “UnitOfWork“, just add reference to DataModel project in WebAPI project.
So our Bootstrapper class becomes,
   public static class Bootstrapper
    {
        public static void Initialise()
        {
            var container = BuildUnityContainer();

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

            // register dependency resolver for WebAPI RC
            GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
        }

        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();

            // register all your components with the container here
            // it is NOT necessary to register your controllers
            
            // e.g. container.RegisterType();        
            container.RegisterType().RegisterType(new HierarchicalLifetimeManager());

            return container;
        }
Like this we can also specify other dependent objects in BuildUnityContainerMethod.
Step 4: Now we need to call the Initialise method of Bootstrapper class. Note , we need the objects as soon as our modules load, therefore we require the container to do its work at the time of application load, therefore go to Global.asax file and add one line to call Initialise method, since this is a static method, we can directly call it using class name,
Bootstrapper.Initialise();
Our global.asax becomes,
using System.Linq;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Newtonsoft.Json;
using WebApi.App_Start;

namespace WebApi
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            //Initialise Bootstrapper
            Bootstrapper.Initialise();

            //Define Formatters
            var formatters = GlobalConfiguration.Configuration.Formatters;
            var jsonFormatter = formatters.JsonFormatter;
            var settings = jsonFormatter.SerializerSettings;
            settings.Formatting = Formatting.Indented;
            // settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            var appXmlType = formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
            formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

            //Add CORS Handler
            GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());
        }
    }
}
Half of the job is done. We now need to touchbase our controller and Service class constructors to utilize the instances already created for them at application load.

Setup Controller

We have already set up unity in our application. There are various methods in which we can inject dependency, like constructor injection, property injection, via service locator. I am here using Constructor Injection, because I find it best method to use with Unity Container to resolve dependency.
Just go to your ProductController, you find your constructor written as,
        /// <summary>
        /// Public constructor to initialize product service instance
        /// </summary>
        public ProductController()
        {
            _productServices =new ProductServices();
        }
Just add a parameter to your constructor that takes your ProductServices reference, like we did below
       /// <summary>
        /// Public constructor to initialize product service instance
        /// </summary>
        public ProductController(IProductServices productServices)
        {
            _productServices = productServices;
        }
And initialize your “productServices” variable with the parameter. In this case when the constructor of the controller is called, It will be served with pre-instantiated service instance, and does not need to create an instance of the service, our unity container did the job of object creation.

Setup Services

For services too, we proceed in a same fashion. Just open your ProductServices class, we see the dependency of UnitOfWork here as,
        /// <summary>
        /// Public constructor.
        /// </summary>
        public ProductServices()
        {
            _unitOfWork = new UnitOfWork();
        }
Again, we perform the same steps ,and pass a parameter of type UnitOfWork to our constructor,
Our code becomes,
        /// <summary>
        /// Public constructor.
        /// </summary>
        public ProductServices(UnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }
Here also we’ll get the pre instantiated object on UnitOfWork. So service does need to worry about creating objects. Remember we did .RegisterType() in Bootstrapper class.
We have now made our components independent.

Running the application

Our job is almost done.We need to run the application, Just hit F5. To our surprise we’ll end up in an error page,
Do you remember we added a test client to our project to test our API in my first article. That test client have a controller too, we need to override its settings to make our application work.Just go to Areas->HelpPage->Controllers->HelpController in WebAPI project like shown below,
Comment out the existing constructors and add a Configuration property like shown below,
      //Remove constructors and existing Configuration property.

        //public HelpController()
        //    : this(GlobalConfiguration.Configuration)
        //{
        //}

        //public HelpController(HttpConfiguration config)
        //{
        //    Configuration = config;
        //}

        //public HttpConfiguration Configuration { get; private set; }

        /// <summary>
        /// Add new Configuration Property
        /// </summary>
        protected static HttpConfiguration Configuration
        {
            get { return GlobalConfiguration.Configuration; }
        }
Our controller code becomes,
using System;
using System.Web.Http;
using System.Web.Mvc;
using WebApi.Areas.HelpPage.Models;

namespace WebApi.Areas.HelpPage.Controllers
{
    /// <summary>
    /// The controller that will handle requests for the help page.
    /// </summary>
    public class HelpController : Controller
    {
        //Remove constructors and existing Configuration property.

        //public HelpController()
        //    : this(GlobalConfiguration.Configuration)
        //{
        //}

        //public HelpController(HttpConfiguration config)
        //{
        //    Configuration = config;
        //}

        //public HttpConfiguration Configuration { get; private set; }

        /// <summary>
        /// Add new Configuration Property
        /// </summary>
        protected static HttpConfiguration Configuration
        {
            get { return GlobalConfiguration.Configuration; }
        }

        public ActionResult Index()
        {
            return View(Configuration.Services.GetApiExplorer().ApiDescriptions);
        }

        public ActionResult Api(string apiId)
        {
            if (!String.IsNullOrEmpty(apiId))
            {
                HelpPageApiModel apiModel = Configuration.GetHelpPageApiModel(apiId);
                if (apiModel != null)
                {
                    return View(apiModel);
                }
            }

            return View("Error");
        }
    }
}
Just run the application, we get,
We alreay have our test client added, but for new readers, I am just again explaining on how to add a test client to our API project.
Just go to Manage Nuget Packages, by right clicking WebAPI project and type WebAPITestClient in searchbox in online packages,
You’ll get “A simple Test Client for ASP.NET Web API”, just add it. You’ll get a help controller in Areas-> HelpPage like shown below,
I have already provided the database scripts and data in my previous article, you can use the same.
Append “/help” in the application url, and you’ll get the test client,
You can test each service by clicking on it.
Service for GetAllProduct,
For Create a new product,
In database, we get new product,
Update product:
We get in database,
Delete product:
In database:
Job done.

Design Flaws

What if I say there are still flaws in this design, the design is still not loosely coupled.
Do you remember what we decided while writing our first application?
Our API talks to Services and Services talk to DataModel. We’ll never allow DataModel talk to APIs for security reasons. But did you notice that when we were registering the type in Bootstrapper class, we also registered the type of UnitOfWork that means we added DataModel as a reference to our API project. This is a design breach. We tried to resolve dependency of a dependency by violating our design and compromising security.
In my next article, we’ll overcome this situation, we’ll try to resolve dependency and its dependency without violating our design and compromising security. In fact we’ll make it more secure and loosely coupled.
In my next article we’ll make use of Managed Extensibility Framework(MEF) to achieve the same.

Conclusion

We now know how to use Unity container to resolve dependency and perform inversion of control.
But still there are some flaws in this design. In my next article, I’ll try to make the system more strong. Till then Happy Coding  :-). You can also download the source code from GitHub. Add the required packages, if they are missing in the source code.

RESTful Day #1: Enterprise Level Application Architecture with Web API’s using Entity Framework, Generic Repository Pattern and Unit of Work


Introduction

I have been practicing, reading a lot about RESTful services for past few days. To my surprise I could not find a complete series of practical implementations of ASP.NET Web API’s on the web. My effort in this series will be to focus on how we can develop basic enterprise level application architecture with Web API’s.
We’ll be discussing less theory and doing more practical to understand how RESTful services can be created using an ORM, we choose Entity Framework here. My first article in the series is to set up a basic architecture of REST service based application. Later on in my upcoming articles, I’ll explain how we can follow best standards to achieve enterprise level architecture.

Roadmap

 My road for the series is as follows,
I’ll purposely use Visual Studio 2010 and .NET Framework 4.0 because there are few implementations that are very hard to find in .NET Framework 4.0, but I’ll make it easy by showing how we can do it.

REST

Here is an extract from Wikipedia,
Unlike SOAP-based web services, there is no “official” standard for RESTful web APIs. This is because REST is an architectural style, while SOAP is a protocol. Even though REST is not a standard per se, most RESTful implementations make use of standards such as HTTP, URI, JSON, and XML.
I agree to it . Let’s do some coding.

Setup database

I am using SQL Server 2008 as a database server. I have provided the sql scripts to create the database in Sql Server, you can use the same to create one.I have given WebApiDb as my database name. My database contains three tables for now, Products, Tokens, User. In this tutorial we’ll only be dealing with product table to perform CURD operations using Web API and Entity framework. We’ll use Tokens and User in my upcoming article. For those who fail to create database through scripts, here is the structure you can follow,

Web API project

Open your Visual Studio, I am using VS 2010, You can use VS version 2010 or above.
Step 1: Create a new Project in your visual studio,
Step 2: There after choose to create ASP.NET MVC 4 Web application, and give it a name of your choice, I gave itWebAPI.
Step 3: Out of different type of project templates shown to you, choose Web API project,
Once done, you’ll get a project structure like shown below, with a default Home and Values controller.
You can choose to delete this ValuesController, as we’ll be using our own controller to learn.

Setup Data Access Layer

Let’s setup or data access layer first. We’ll be using Entity Framework 5.0 to talk to database. We’ll use Generic Repository Pattern and Unit of work pattern to standardize our layer.
Let’s have a look at the standard definition of Entity Framework given by Microsoft:
“The Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects. The Entity Framework’s ORM implementation provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals.”
In simple language, Entity framework is an Object/Relational Mapping (ORM) framework. It is an enhancement to ADO.NET, an upper layer to ADO.NET that gives developers an automated mechanism for accessing and storing the data in the database.
Step 1 : Create a new class library in your visual studio, and name it DataModel as shown below,
Step2: In the same way, create one more project i.e. again a class library and call it BusinessEntities,
I’ll explain the use of this class library soon.
Step 3: Move on to your DataModel project , right click on it and add a new item, in the list shown, choose ADO.NET Data Model, and name it WebApiDataModel.edmx.
The file .edmx will contain the database information of our database that we created earlier, let’s set up this. You’ll be presented a wizard like follows,
Choose, generate from database. Choose Microsoft SQl Server like shown in the following image,
Click continue, then provide the credentials of your database, i.e. WebAPIdb, and connect it,
You’ll get a screen, showing the connection string of the database we chose,
Provide the name of the connection string as WebApiDbEntities and click Next.
Choose all the database objects, check all the check boxes, and provide a name for the model. I gave it a name WebApiDbModel.
Once you finish this wizard, you’ll get the schema ready in your datamodel project as follows,
We’ve got our schema in-place using Entity Framework. But few work is still remaining. We need our data context class and entities through which we’ll communicate with database.
So, moving on to next step.
Step 3: Click on tools in Visual Studio and open Extension manager. We need to get db context generator for our datamodel. We can also do it using default code generation item by right clicking in the edmx view and add code generation item, but that will generate object context class and that is heavier than db context. I want light weighted db context class to be created, so we’ll use extension manager to add a package and then create a db context class.
Search for Entity Framework Dbcontext generator in online gallery and select the one for EF 5.x like below,
I guess you need to restart Visual studio to get that into your templates.
Step 4 : Now right click in the .edmx file schema designer and choose “Add Code Generation Item..”.
Step 5 : Now you’ll see that we have got the template for the extension that we added, select that EF 5.x DbContext Generator and click Add.
After adding this we’ll get the db context class and its properties, this class is responsible for all database transactions that we need to perform, so our structure looks like as shown below,
Wow, we ended up in errors. But we got our db context class and our entity models, You can see them in our DataModel project. Errors? Nothing to worry about, it’s just we did not reference entity framework in our project. We’ll do it right away.
Step 6 : Go to Tools -> Library Packet Manager->Packet manager Console. You’ll get the console in left bottom of Visual studio.
Select dataModel project and write a command “Install-Package EntityFramework –Version 5.0.0” to install Entity Framework 5 in our DataModel project.
Press enter. And all the errors get resolved.

Generic Repository and Unit of Work

You can read about repository pattern and creating a repository in detail from my article :https://codeteddy.com/2013/09/03/learning-mvc-part-5repository-pattern-in-mvc3-application-with-entity-framework/.
Just to list down the benefits of Repository pattern,
  • It centralizes the data logic or Web service access logic.
  • It provides a substitution point for the unit tests.
  • It provides a flexible architecture that can be adapted as the overall design of the application evolves.
We’ll create a generic repository that works for all our entities. Creating repositories for each and every entity may result in lots of duplicate code in large projects.For creating Generic Repository you can follow : https://codeteddy.com/2013/09/03/learning-mvc-part-6-generic-repository-pattern-in-mvc3-application-with-entity-framework/
Step 1: Add a folder named GenericRepository in DataModel project and to that folder add a class named Generic Repository. Add following code to that class, that servers as a template based generic code for all the entities that will interact with database,
#region Using Namespaces...

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;

#endregion

namespace DataModel.GenericRepository
{
/// <summary>
    /// Generic Repository class for Entity Operations
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    public class GenericRepository where TEntity : class
    {
#region Private member variables...
internal WebApiDbEntities Context;
internal DbSet DbSet;
#endregion

#region Public Constructor...
/// <summary>
        /// Public Constructor,initializes privately declared local variables.
        /// </summary>
        /// <param name="context"></param>
        public GenericRepository(WebApiDbEntities context)
        {
this.Context = context;
this.DbSet = context.Set();
        }
#endregion

#region Public member methods...

/// <summary>
        /// generic Get method for Entities
        /// </summary>
        /// <returns></returns>
        public virtual IEnumerable Get()
        {
            IQueryable query = DbSet;
return query.ToList();
        }

/// <summary>
        /// Generic get method on the basis of id for Entities.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual TEntity GetByID(object id)
        {
return DbSet.Find(id);
        }

/// <summary>
        /// generic Insert method for the entities
        /// </summary>
        /// <param name="entity"></param>
        public virtual void Insert(TEntity entity)
        {
            DbSet.Add(entity);
        }

/// <summary>
        /// Generic Delete method for the entities
        /// </summary>
        /// <param name="id"></param>
        public virtual void Delete(object id)
        {
            TEntity entityToDelete = DbSet.Find(id);
            Delete(entityToDelete);
        }

/// <summary>
        /// Generic Delete method for the entities
        /// </summary>
        /// <param name="entityToDelete"></param>
        public virtual void Delete(TEntity entityToDelete)
        {
if (Context.Entry(entityToDelete).State == EntityState.Detached)
            {
                DbSet.Attach(entityToDelete);
            }
            DbSet.Remove(entityToDelete);
        }

/// <summary>
        /// Generic update method for the entities
        /// </summary>
        /// <param name="entityToUpdate"></param>
        public virtual void Update(TEntity entityToUpdate)
        {
            DbSet.Attach(entityToUpdate);
            Context.Entry(entityToUpdate).State = EntityState.Modified;
        }

/// <summary>
        /// generic method to get many record on the basis of a condition.
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public virtual IEnumerable GetMany(Func<TEntity, bool> where)
        {
return DbSet.Where(where).ToList();
        }

/// <summary>
        /// generic method to get many record on the basis of a condition but query able.
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public virtual IQueryable GetManyQueryable(Func<TEntity, bool> where)
        {
return DbSet.Where(where).AsQueryable();
        }

/// <summary>
        /// generic get method , fetches data for the entities on the basis of condition.
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public TEntity Get(Func<TEntity, Boolean> where)
        {
return DbSet.Where(where).FirstOrDefault();
        }

/// <summary>
        /// generic delete method , deletes data for the entities on the basis of condition.
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public void Delete(Func<TEntity, Boolean> where)
        {
            IQueryable objects = DbSet.Where(where).AsQueryable();
foreach (TEntity obj in objects)
                DbSet.Remove(obj);
        }

/// <summary>
        /// generic method to fetch all the records from db
        /// </summary>
        /// <returns></returns>
        public virtual IEnumerable GetAll()
        {
return DbSet.ToList();
        }

/// <summary>
        /// Inclue multiple
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="include"></param>
        /// <returns></returns>
        public IQueryable GetWithInclude(
            System.Linq.Expressions.Expression<Func<TEntity, 
bool>> predicate, params string[] include)
        {
            IQueryable query = this.DbSet;
            query = include.Aggregate(query, (current, inc) => current.Include(inc));
return query.Where(predicate);
        }

/// <summary>
        /// Generic method to check if entity exists
        /// </summary>
        /// <param name="primaryKey"></param>
        /// <returns></returns>
        public bool Exists(object primaryKey)
        {
return DbSet.Find(primaryKey) != null;
        }

/// <summary>
        /// Gets a single record by the specified criteria (usually the unique identifier)
        /// </summary>
        /// <param name="predicate">Criteria to match on</param>
        /// <returns>A single record that matches the specified criteria</returns>
        public TEntity GetSingle(Func<TEntity, bool> predicate)
        {
return DbSet.Single(predicate);
        }

/// <summary>
        /// The first record matching the specified criteria
        /// </summary>
        /// <param name="predicate">Criteria to match on</param>
        /// <returns>A single record containing the first record matching the specified criteria</returns>
        public TEntity GetFirst(Func<TEntity, bool> predicate)
        {
return DbSet.First(predicate);
        }


#endregion
    }
}

Unit of Work

Again I’ll not explain in detail what Unit of Work is. You can google about the theory or follow my existing article on MVC with Unit of Work.
To give a heads up, again from my existing article, the important responsibilities of Unit of Work are,
  • To manage transactions.
  • To order the database inserts, deletes, and updates.
  • To prevent duplicate updates. Inside a single usage of a Unit of Work object, different parts of the code may mark the same Invoice object as changed, but the Unit of Work class will only issue a single UPDATE command to the database.
The value of using a Unit of Work pattern is to free the rest of our code from these concerns so that you can otherwise concentrate on business logic.
Step 1: Create a folder named UnitOfWork, add a class to that folder named UnitOfWork.cs,
Add GenericRepository properties for all the three entities that we got. The class also implementsIDisposableinterface and it’s method Dispose to free up connections and objects. The class will be as follows,
#region Using Namespaces...

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Data.Entity.Validation;
using DataModel.GenericRepository;

#endregion

namespace DataModel.UnitOfWork
{
/// <summary>
    /// Unit of Work class responsible for DB transactions
    /// </summary>
    public class UnitOfWork : IDisposable
    {
#region Private member variables...

private WebApiDbEntities _context = null;
private GenericRepository _userRepository;
private GenericRepository _productRepository;
private GenericRepository _tokenRepository;
#endregion

public UnitOfWork()
        {
            _context = new WebApiDbEntities();
        }

#region Public Repository Creation properties...

/// <summary>
        /// Get/Set Property for product repository.
        /// </summary>
        public GenericRepository ProductRepository
        {
get
            {
if (this._productRepository == null)
this._productRepository = new GenericRepository(_context);
return _productRepository;
            }
        }

/// <summary>
        /// Get/Set Property for user repository.
        /// </summary>
        public GenericRepository UserRepository
        {
get
            {
if (this._userRepository == null)
this._userRepository = new GenericRepository(_context);
return _userRepository;
            }
        }

/// <summary>
        /// Get/Set Property for token repository.
        /// </summary>
        public GenericRepository TokenRepository
        {
get
            {
if (this._tokenRepository == null)
this._tokenRepository = new GenericRepository(_context);
return _tokenRepository;
            }
        }
#endregion

#region Public member methods...
/// <summary>
        /// Save method.
        /// </summary>
        public void Save()
        {
try
            {
                _context.SaveChanges();
            }
catch (DbEntityValidationException e)
            {

var outputLines = new List<string>();
foreach (var eve in e.EntityValidationErrors)
                {
                    outputLines.Add(string.Format(
"{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:", DateTime.Now, 
                        eve.Entry.Entity.GetType().Name, eve.Entry.State));
foreach (var ve in eve.ValidationErrors)
                    {
                        outputLines.Add(string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage));
                    }
                }
                System.IO.File.AppendAllLines(@"C:\errors.txt", outputLines);

throw e;
            }

        }

#endregion

#region Implementing IDiosposable...

#region private dispose variable declaration...
private bool disposed = false; 
#endregion

/// <summary>
        /// Protected Virtual Dispose method
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
if (!this.disposed)
            {
if (disposing)
                {
                    Debug.WriteLine("UnitOfWork is being disposed");
                    _context.Dispose();
                }
            }
this.disposed = true;
        }

/// <summary>
        /// Dispose method
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        } 
#endregion
    }
}
Now we have completely set up our data access layer, and our project structure looks like as shown below,

Setup Business Entities

Remember, we created a business entities project. You may wonder, we already have database entities to interact with database then why do we need Business Entities? The answer is as simple as that, we are trying to follow a proper structure of communication, and one would never want to expose the database entities to the end client, in our case is Web API, it involves lot of risk. Hackers may manipulate the details and get accessto your database.Instead we’ll use database entities in our business logic layer and use Business Entities as transfer objects to communicate between business logic and Web API project. So business entities may have different names but, their properties remains same as database entities. In our case we’ll add same name business entity classes appendint word “Entity” to them in our BusinessEntity project. So we’ll end up having three classes as follows,

Product entity

public class ProductEntity
    {
public int ProductId { get; set; }
public string ProductName { get; set; }
    }

Token entity

public class TokenEntity
    {
public int TokenId { get; set; }
public int UserId { get; set; }
public string AuthToken { get; set; }
public System.DateTime IssuedOn { get; set; }
public System.DateTime ExpiresOn { get; set; }
    }

User entity

public class UserEntity
    {
public int UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Name { get; set; }
    }

Setup Business Services Project

Add a new class library to the solution named BusinessServices. This layer will act as our business logic layer. Note that, we can make use of our API controllers to write business logic, but I am trying to segregate my business logic in an extra layer so that if in future I want to use WCF, MVC, ASP.NET Web Pages or any other application as my presentation layer then I can easily integrate my Business logic layer in it.
We’ll make this layer testable, so we need to create an interface in and declare CURD operations that we need to perform over product table.Before we proceed, add the reference of BusinessEntities project and DataModel project to this newly created project
Step 1 : Create an interface named IProductServices and add following code to it for CURD operations methods,
using System.Collections.Generic;
using BusinessEntities;

namespace BusinessServices
{
/// <summary>
    /// Product Service Contract
    /// </summary>
    public interface IProductServices
    {
        ProductEntity GetProductById(int productId);
        IEnumerable GetAllProducts();
int CreateProduct(ProductEntity productEntity);
bool UpdateProduct(int productId,ProductEntity productEntity);
bool DeleteProduct(int productId);
    }
}
Step 2 : Create a class to implement this interface.name that class ProductServices,
The class contains a private variable of UnitOfWork and a constructor to initialize that variable,
private readonly UnitOfWork _unitOfWork;

/// <summary>
        /// Public constructor.
        /// </summary>
        public ProductServices()
        {
            _unitOfWork = new UnitOfWork();
        }
We have decided not to expose our db entities to Web API project, so we need something to map the db entities data to my business entity classes. We’ll make use of AutoMapper.You can read about AutoMapper in my this article.
Step 3: Just right click project-> Extension manager, search for AutoMapper in online galary and add to BusinessServices project,
Step 4: Implement methods in ProductServices class,
Add following code to the class,
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using AutoMapper;
using BusinessEntities;
using DataModel;
using DataModel.UnitOfWork;

namespace BusinessServices
{
/// <summary>
    /// Offers services for product specific CRUD operations
    /// </summary>
    public class ProductServices:IProductServices
    {
private readonly UnitOfWork _unitOfWork;

/// <summary>
        /// Public constructor.
        /// </summary>
        public ProductServices()
        {
            _unitOfWork = new UnitOfWork();
        }

/// <summary>
        /// Fetches product details by id
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public BusinessEntities.ProductEntity GetProductById(int productId)
        {
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
            {
                Mapper.CreateMap();
var productModel = Mapper.Map(product);
return productModel;
            }
return null;
        }

/// <summary>
        /// Fetches all the products.
        /// </summary>
        /// <returns></returns>
        public IEnumerable GetAllProducts()
        {
var products = _unitOfWork.ProductRepository.GetAll().ToList();
if (products.Any())
            {
                Mapper.CreateMap();
var productsModel = Mapper.Map<List, List>(products);
return productsModel;
            }
return null;
        }

/// <summary>
        /// Creates a product
        /// </summary>
        /// <param name="productEntity"></param>
        /// <returns></returns>
        public int CreateProduct(BusinessEntities.ProductEntity productEntity)
        {
using (var scope = new TransactionScope())
            {
var product = new Product
                {
                    ProductName = productEntity.ProductName
                };
                _unitOfWork.ProductRepository.Insert(product);
                _unitOfWork.Save();
                scope.Complete();
return product.ProductId;
            }
        }

/// <summary>
        /// Updates a product
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="productEntity"></param>
        /// <returns></returns>
        public bool UpdateProduct(int productId, BusinessEntities.ProductEntity productEntity)
        {
var success = false;
if (productEntity != null)
            {
using (var scope = new TransactionScope())
                {
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
                    {
                        product.ProductName = productEntity.ProductName;
                        _unitOfWork.ProductRepository.Update(product);
                        _unitOfWork.Save();
                        scope.Complete();
                        success = true;
                    }
                }
            }
return success;
        }

/// <summary>
        /// Deletes a particular product
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public bool DeleteProduct(int productId)
        {
var success = false;
if (productId > 0)
            {
using (var scope = new TransactionScope())
                {
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
                    {

                        _unitOfWork.ProductRepository.Delete(product);
                        _unitOfWork.Save();
                        scope.Complete();
                        success = true;
                    }
                }
            }
return success;
        }
    }
}
Let me explain the idea of the code. We have 5 methods as follows,
  1. To get product by id ( GetproductById ) : We call repository to get the product by id. Id comes as a parameter from the calling method to that service method. It returns the product entity from the database. Note that it will not return the exact db entity, instead we’ll map it with our business entity usingAutoMapper and return it to calling method.
    /// <summary>
            /// Fetches product details by id
            /// </summary>
            /// <param name="productId"></param>
            /// <returns></returns>
            public BusinessEntities.ProductEntity GetProductById(int productId)
            {
    var product = _unitOfWork.ProductRepository.GetByID(productId);
    if (product != null)
                {
                    Mapper.CreateMap();
    var productModel = Mapper.Map(product);
    return productModel;
                }
    return null;
            }
  2. Get all products from database (GetAllProducts) : This method returns all the products residing in database, again we make use of AutoMapper to map the list and return back.
    /// <summary>
            /// Fetches all the products.
            /// </summary>
            /// <returns></returns>
            public IEnumerable GetAllProducts()
            {
    var products = _unitOfWork.ProductRepository.GetAll().ToList();
    if (products.Any())
                {
                    Mapper.CreateMap();
    var productsModel = Mapper.Map<List, List>(products);
    return productsModel;
                }
    return null;
            }
  3. Create a new product (CreateProduct) : This method takes productBusinessEntity as an argument and creates a new object of actual database entity and insert it using unit of work.
    /// <summary>
            /// Creates a product
            /// </summary>
            /// <param name="productEntity"></param>
            /// <returns></returns>
            public int CreateProduct(BusinessEntities.ProductEntity productEntity)
            {
    using (var scope = new TransactionScope())
                {
    var product = new Product
                    {
                        ProductName = productEntity.ProductName
                    };
                    _unitOfWork.ProductRepository.Insert(product);
                    _unitOfWork.Save();
                    scope.Complete();
    return product.ProductId;
                }
            }
I guess you can now write update and delete methods. So I am writing the code of complete class,
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using AutoMapper;
using BusinessEntities;
using DataModel;
using DataModel.UnitOfWork;

namespace BusinessServices
{
/// <summary>
    /// Offers services for product specific CRUD operations
    /// </summary>
    public class ProductServices:IProductServices
    {
private readonly UnitOfWork _unitOfWork;

/// <summary>
        /// Public constructor.
        /// </summary>
        public ProductServices()
        {
            _unitOfWork = new UnitOfWork();
        }

/// <summary>
        /// Fetches product details by id
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public BusinessEntities.ProductEntity GetProductById(int productId)
        {
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
            {
                Mapper.CreateMap();
var productModel = Mapper.Map(product);
return productModel;
            }
return null;
        }

/// <summary>
        /// Fetches all the products.
        /// </summary>
        /// <returns></returns>
        public IEnumerable GetAllProducts()
        {
var products = _unitOfWork.ProductRepository.GetAll().ToList();
if (products.Any())
            {
                Mapper.CreateMap();
var productsModel = Mapper.Map<List, List>(products);
return productsModel;
            }
return null;
        }

/// <summary>
        /// Creates a product
        /// </summary>
        /// <param name="productEntity"></param>
        /// <returns></returns>
        public int CreateProduct(BusinessEntities.ProductEntity productEntity)
        {
using (var scope = new TransactionScope())
            {
var product = new Product
                {
                    ProductName = productEntity.ProductName
                };
                _unitOfWork.ProductRepository.Insert(product);
                _unitOfWork.Save();
                scope.Complete();
return product.ProductId;
            }
        }

/// <summary>
        /// Updates a product
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="productEntity"></param>
        /// <returns></returns>
        public bool UpdateProduct(int productId, BusinessEntities.ProductEntity productEntity)
        {
var success = false;
if (productEntity != null)
            {
using (var scope = new TransactionScope())
                {
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
                    {
                        product.ProductName = productEntity.ProductName;
                        _unitOfWork.ProductRepository.Update(product);
                        _unitOfWork.Save();
                        scope.Complete();
                        success = true;
                    }
                }
            }
return success;
        }

/// <summary>
        /// Deletes a particular product
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public bool DeleteProduct(int productId)
        {
var success = false;
if (productId > 0)
            {
using (var scope = new TransactionScope())
                {
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
                    {

                        _unitOfWork.ProductRepository.Delete(product);
                        _unitOfWork.Save();
                        scope.Complete();
                        success = true;
                    }
                }
            }
return success;
        }
    }
}
Job done at business service level. Let’s move on to API controller to call these methods.

Setup WebAPI project

Step1 : Just add the reference of BusinessEntity and BusinessService in the WebAPI project, our architecture becomes like this,
Step 2: Add a new WebAPI controller in Controller folder. Right click Controller folder and add a new controller.
We get a controller as follows,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace WebApi.Controllers
{
public class ProductController : ApiController
    {
// GET api/product
        public IEnumerable<string> Get()
        {
return new string[] { "value1", "value2" };
        }

// GET api/product/5
        public string Get(int id)
        {
return "value";
        }

// POST api/product
        public void Post([FromBody]string value)
        {
        }

// PUT api/product/5
        public void Put(int id, [FromBody]string value)
        {
        }

// DELETE api/product/5
        public void Delete(int id)
        {
        }
    }
}
We get HTTP VERBS as method names. Web API is smart enough to recognize request with the name of the VERB itself. In our case we are doing CRUD operations, so we don’t need to change the names of the method, we just needed this. We only have to write calling logic inside these methods. In my upcoming articles of the series, we will figure out how we can define new routes and provide method names of our choice with those routes.
Step 3: Add logic to call Business Service methods, just make an object of Business Service and call its respective methods, our Controller class becomes like,
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using BusinessEntities;
using BusinessServices;

namespace WebApi.Controllers
{
public class ProductController : ApiController
    {

private readonly IProductServices _productServices;

#region Public Constructor

/// <summary>
        /// Public constructor to initialize product service instance
        /// </summary>
        public ProductController()
        {
            _productServices =new ProductServices();
        }

#endregion

// GET api/product
        public HttpResponseMessage Get()
        {
var products = _productServices.GetAllProducts();
if (products != null)
            {
var productEntities = products as List ?? products.ToList();
if (productEntities.Any())
return Request.CreateResponse(HttpStatusCode.OK, productEntities);
            }
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Products not found");
        }

// GET api/product/5
        public HttpResponseMessage Get(int id)
        {
var product = _productServices.GetProductById(id);
if (product != null)
return Request.CreateResponse(HttpStatusCode.OK, product);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for this id");
        }

// POST api/product
        public int Post([FromBody] ProductEntity productEntity)
        {
return _productServices.CreateProduct(productEntity);
        }

// PUT api/product/5
        public bool Put(int id, [FromBody]ProductEntity productEntity)
        {
if (id  > 0)
            {
return _productServices.UpdateProduct(id, productEntity);
            }
return false;
        }

// DELETE api/product/5
        public bool Delete(int id)
        {
if (id > 0)
return _productServices.DeleteProduct(id);
return false;
        }
    }
}
Just run the application, we get,
But now how do we test our API? We don’t have client. Guys, we’ll not be writing a client now to test it.We’ll add a package that will do all our work.
Just go to Manage Nuget Packages, by right clicking WebAPI project and type WebAPITestClient in searchbox in online packages,
You’ll get “A simple Test Client for ASP.NET Web API”, just add it. You’ll get a help controller in Areas-> HelpPage like shown below,

Running the Application

Before running the application, I have put some test data in our product table.
Just hit F5, you get the same page as you got earlier, just append “/help” in its url, and you’ll get the test client,
You can test each service by clicking on it.
Service for GetAllProduct,
For Create a new product,
In database, we get new product,
Update product:
We get in database,
Delete product:
In database:
Job done.

Design Flaws

  1. Architecture is tightly coupled. IOC (Inversion of Control) needs to be there.
  2. We cannot define our own routes.
  3. No exception handling and logging.
  4. No unit tetsts.

Conclusion

We now know how to create a WebAPI and perform CRUD operations using n layered architecture.
But still there are some flaws in this design.In my next two articles I’ll explain how to make the system loosely coupled using Dependency Injection Principle. We’ll also cover all the design flaws to make our design better and stronger. Till then Happy Coding J You can also download the source code from GitHub.

Learning MVC Part 6: Generic Repository Pattern in MVC3 Application with Entity Framework


Introduction

Creating a Generic Repository pattern in an MVC3 application with Entity Framework is the last topic that we are about to cover in our journey of learning MVC.
The article will focus on Unit of Work Pattern and Repository Pattern, and shows how to perform CRUD operations in an MVC application when there could be a possibility of creating more than one repository class. To overcome this possibility and overhead, we make a Generic Repository class for all other repositories and implement a Unit of Work pattern to provide abstraction.

Our roadmap towards Learning MVC

Just to remind our full roadmap towards learning MVC,

Pre-requisites

There are few pre-requisites before we start with the article,
  1. We have running sample application that we created in fifth part of the article series.
  2. We have Entity Framework 4.1 package or DLL on our local file system.
  3. We understand how MVC application is created (follow second part of the series).

Why Generic Repository

We have already discussed what Repository Pattern is and why do we need Repository Pattern in our last article. We created a User Repository for performing CRUD operations, but think of the scenario where we need 10 such repositories.
Are we going to create these classes? Not good, it results in a lot of redundant code. So to overcome this situation we’ll create a Generic Repository class that will be called by a property to create a new repository thus we do not result in lot of classes and also escape redundant code too. Moreover we save a lot of time that could be wasted creating those classes.

Unit of Work Pattern

According to Martin Fowler 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.”
From MSDN, The Unit of Work pattern isn’t necessarily something that you will explicitly build yourself, but the pattern shows up in almost every persistence tool. The ITransaction interface in NHibernate, the DataContextclass in LINQ to SQL, and the ObjectContext class in the Entity Framework are all examples of a Unit of Work. For that matter, the venerable DataSet can be used as a Unit of Work.
Other times, you may want to write your own application-specific Unit of Work interface or class that wraps the inner Unit of Work from your persistence tool. You may do this for a number of reasons. You might want to add application-specific logging, tracing, or error handling to transaction management. Perhaps you want to encapsulate the specifics of your persistence tooling from the rest of the application. You might want this extra encapsulation to make it easier to swap out persistence technologies later. Or you might want to promote testability in your system. Many of the built-in Unit of Work implementations from common persistence tools are difficult to deal with in automated unit testing scenarios.”
The Unit of Work class can have methods to mark entities as modified, newly created, or deleted. The Unit of Work will also have methods to commit or roll back all of the changes as well.
The important responsibilities of Unit of Work are,
  • To manage transactions.
  • To order the database inserts, deletes, and updates.
  • To prevent duplicate updates. Inside a single usage of a Unit of Work object, different parts of the code may mark the same Invoice object as changed, but the Unit of Work class will only issue a single UPDATE command to the database.
The value of using a Unit of Work pattern is to free the rest of our code from these concerns so that you can otherwise concentrate on business logic.

Why use Unit of Work?

Again Martin Fowler statements, “When you’re pulling data in and out of a database, it’s important to keep track of what you’ve changed; otherwise, that data won’t be written back into the database. Similarly you have to insert new objects you create and remove any objects you delete.
You can change the database with each change to your object model, but this can lead to lots of very small database calls, which ends up being very slow. Furthermore it requires you to have a transaction open for the whole interaction, which is impractical if you have a business transaction that spans multiple requests. The situation is even worse if you need to keep track of the objects you’ve read so you can avoid inconsistent reads.
A Unit of Work keeps track and takes responsibility of everything you do during a business transaction that can affect the database. When you’re done, it figures out everything that needs to be done to alter the database as a result of your work.”
You see I don’t have to concentrate much on theory, we already have great definitions existing, all we needed is to stack them in a correct format.

Using the Unit of Work

One of the best ways to use the Unit of Work pattern is to allow disparate classes and services to take part in a single logical transaction. The key point here is that you want the disparate classes and services to remain ignorant of each other while being able to enlist in a single transaction. Traditionally, you’ve been able to do this by using transaction coordinators like MTS/COM+ or the newer System.Transactions namespace. Personally, I prefer using the Unit of Work pattern to allow unrelated classes and services to take part in a logical transaction because I think it makes the code more explicit, easier to understand, and simpler to unit test(From MSDN).

Creating a Generic Repository

Cut the Redundancy…
Step 1: Open up our existing MVC3 application created in Part5 in Visual Studio.
Step2: Right click Learning MVC project folder and create a folder named GenericRepository and add a class namedGenericRepository.cs to that folder.
The code of the GenericRepository.cs class is as follows:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;

namespace LearningMVC.GenericRepository
{
public class GenericRepository where TEntity : class
{
internal MVCEntities context;
internal DbSet dbSet;

public GenericRepository(MVCEntities context)
{
this.context = context;
this.dbSet = context.Set();
}

public virtual IEnumerable Get()
{
IQueryable query = dbSet;
return query.ToList();
}

public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}

public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}

public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}

public virtual void Delete(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}

public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
}
}

We can see, we have created the generic methods and the class as well is generic, when instantiating this class we can pass any model on which the class will work as a repository and serve the purpose.
TEntity is any model/domain/entity class. MVCEntities is our DBContext as discussed in earlier parts.
Step 3: Implementing UnitOfWork: Create a folder named UnitOfWork under LearningMVC project, and add a class UnitOfWork.cs to that folder.
The code of the class is as follows:
using System;
using LearningMVC.GenericRepository;

namespace LearningMVC.UnitOfWork
{
public class UnitOfWork : IDisposable
{
private MVCEntities context = new MVCEntities();
private GenericRepository userRepository;

public GenericRepository UserRepository
{
get
{
if (this.userRepository == null)
this.userRepository = new GenericRepository(context);
return userRepository;
}
}

public void Save()
{
context.SaveChanges();
}

private bool disposed = false;

protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}

We see the class implements IDisposable interface for objects of this class to be disposed.
We create object of DBContext in this class, note that earlier it was used to be passed in Repository class from a controller.
Now it’s time to create our User Repository. We see in the code itself that, simply a variable named userRepositoryis declared as private GenericRepository userRepository; of type GenericRepository serving User entity to TEntity template.
Then a property is created for the same userRepository variable in a very simplified manner,
public GenericRepository UserRepository
{
    get
    {
        if (this.userRepository == null)
            this.userRepository = new GenericRepository(context);
        return userRepository;
    }
}
I.e., mere 6-7 lines of code. Guess what? Our UserRepository is created.
(Taken from Google)
You see it was as simple as that, you can create as many repositories you want by just creating simple properties, and no need to create separate classes. And now you can complete the rest of the story by yourself, confused???? Yes it’sDBOperations, let’s do it.
Step 4: In MyController, declare a variable unitOfWork as:
private UnitOfWork.UnitOfWork unitOfWork = new UnitOfWork.UnitOfWork();
Now this unitOfWork instance of UnitOfWork class holds all th repository properties,if we press “.” After it, it will show the repositories.So we can choose any of the repositories created and perform CRUD operations on them.
E.g. our Index action:
public ActionResult Index()
{
    var userList = from user in unitOfWork.UserRepository.Get() select user;
    var users = new List();
    if (userList.Any())
    {
        foreach (var user in userList)
        {
            users.Add(new LearningMVC.Models.UserList() { UserId = user.UserId, 
              Address = user.Address, Company = user.Company, 
              FirstName = user.FirstName, LastName = user.LastName, 
              Designation = user.Designation, EMail = user.EMail, PhoneNo = user.PhoneNo });
        }
    }
    ViewBag.FirstName = "My First Name";
    ViewData["FirstName"] = "My First Name";
    if(TempData.Any())
    {
        var tempData = TempData["TempData Name"];
    }
    return View(users);
}
Here,
  • unitOfWork.UserRepository ­­> Accessing UserRepository.
  • unitOfWork.UserRepository.Get() -> Accessing Generic Get() method to get all users.
Earlier we used to have MyController constructor like:
public MyController()
{
    this.userRepository = new UserRepository(new MVCEntities());
}
Now, no need to write that constructor, in fact you can remove the UserRepository class and Interface we created in part 5 of Learning MVC.
I hope you can write the Actions for rest of the CRUD operations as well.

Details

public ActionResult Details(int id)
{
    var userDetails = unitOfWork.UserRepository.GetByID(id);
    var user = new LearningMVC.Models.UserList();
    if (userDetails != null)
    {
        user.UserId = userDetails.UserId;
        user.FirstName = userDetails.FirstName;
        user.LastName = userDetails.LastName;
        user.Address = userDetails.Address;
        user.PhoneNo = userDetails.PhoneNo;
        user.EMail = userDetails.EMail;
            user.Company = userDetails.Company;
        user.Designation = userDetails.Designation;
    }
    return View(user);
}
 
Create:
[HttpPost]
public ActionResult Create(LearningMVC.Models.UserList userDetails)
{
    try
    {
        var user = new User();
        if (userDetails != null)
        {
            user.UserId = userDetails.UserId;
            user.FirstName = userDetails.FirstName;
            user.LastName = userDetails.LastName;
            user.Address = userDetails.Address;
            user.PhoneNo = userDetails.PhoneNo;
            user.EMail = userDetails.EMail;
            user.Company = userDetails.Company;
            user.Designation = userDetails.Designation;
        }
        unitOfWork.UserRepository.Insert(user);
        unitOfWork.Save();
        return RedirectToAction("Index");
          }
    catch
    {
        return View();
    }
}
 
Edit:
public ActionResult Edit(int id)
{
    var userDetails = unitOfWork.UserRepository.GetByID(id);
    var user = new LearningMVC.Models.UserList();
    if (userDetails != null)
    {
        user.UserId = userDetails.UserId;
        user.FirstName = userDetails.FirstName;
        user.LastName = userDetails.LastName;
        user.Address = userDetails.Address;
        user.PhoneNo = userDetails.PhoneNo;
        user.EMail = userDetails.EMail;
        user.Company = userDetails.Company;
        user.Designation = userDetails.Designation;
      }
    return View(user);
}

[HttpPost]
public ActionResult Edit(int id, User userDetails)
{
TempData[TempData Name”] = Akhil”;

try
{
var user = unitOfWork.UserRepository.GetByID(id);
user.FirstName = userDetails.FirstName;
user.LastName = userDetails.LastName;
user.Address = userDetails.Address;
user.PhoneNo = userDetails.PhoneNo;
user.EMail = userDetails.EMail;
user.Company = userDetails.Company;
user.Designation = userDetails.Designation;
unitOfWork.UserRepository.Update(user);
unitOfWork.Save();
return RedirectToAction(Index”);
}

 
Delete:
public ActionResult Delete(int id)
{
    var user = new LearningMVC.Models.UserList();
    var userDetails = unitOfWork.UserRepository.GetByID(id);

if (userDetails != null)
{
user.FirstName = userDetails.FirstName;
user.LastName = userDetails.LastName;
user.Address = userDetails.Address;
user.PhoneNo = userDetails.PhoneNo;
user.EMail = userDetails.EMail;
user.Company = userDetails.Company;
user.Designation = userDetails.Designation;
}
return View(user);
}

[HttpPost]
public ActionResult Delete(int id, LearningMVC.Models.UserList userDetails)
{
try
{
var user = unitOfWork.UserRepository.GetByID(id);

if (user != null)
{
unitOfWork.UserRepository.Delete(id);
unitOfWork.Save();
}

return RedirectToAction(Index”);
}
catch
{
return View();
}
}

 
Note: Images are taken from Google images.

Conclusion

We now know how to make generic repositories too, and perform CRUD operations using it.

We have also learnt UnitOfWork pattern in detail. Now you are qualified and confident enough to apply these concepts in your enterprise applications. This was the last part of this MVC series, let me know if you feel to discuss any topic in particular or we can also start any other series as well.

Read more:

Other Series

My other series of articles:

For more informative articles visit my Blog.

For more technical articles you can reach out to CodeTeddy.

Learning MVC – Part 5:Repository Pattern in MVC3 Application with Entity Framework


Introduction

In our last four articles, we learnt almost everything about how to create an MVC application and how to communicate with database using the same application.
In the third part of learning MVC, we learnt communication between MVC application and database usingEntityFramework, so I am referring to the same context. In this article, I’ll focus on how to implement a Repository Pattern in the same MVC application, therefore moving ahead a step towards architectural approach of developing an enterprise application.

Our Roadmap

Just to remind you of our full roadmap towards learning MVC:

Pre-requisites

There are a few pre-requisites before we start with the article:
  1. We have running sample application that we created in the third part of the article series.
  2. We have EntityFramework 4.1 package or DLL on our local file system.
  3. We understand how the MVC application is created.

Repository Pattern

Very few authors explain the concept and jump directly over the practical implementation of the pattern. So, first let us understand what is repository pattern? Why should we use it?
In simple terms, a repository basically works as a mediator between our business logic layer and our data access layer of the application. Sometimes, it would be troublesome to expose the data access mechanism directly to business logic layer, it may result in redundant code for accessing data for similar entities or it may result in a code that is hard to test or understand. To overcome these kinds of issues, and to write an Interface driven and test driven code to access data, we use Repository Pattern. The repository makes queries to the data source for the data, thereafter maps the data from the data source to a business entity/domain object, finally and persists the changes in the business entity to the data source. According to MSDN, a repository separates the business logic from the interactions with the underlying data source or Web service. The separation between the data and business tiers has three benefits:
  • It centralizes the data logic or Web service access logic.
  • It provides a substitution point for the unit tests.
  • It provides a flexible architecture that can be adapted as the overall design of the application evolves.
When we use Entity Framework, as we did in our last application created, we were calling the Entity Framework class object in the controller class for accessing the entity classes. Now we can say that that system was somewhat a tightly coupled system. To overcome this situation, as we discussed, we’ll implement Repository Pattern.
In Repository, we write our whole business logic of CRUD operations with the help of Entity Framework classes, that will not only result in meaningful test driven code but will also reduce our controller code of accessing data.

Creating Repository

Creating Repository is not as tough at it sounds to be, once you implement this by your own, you’ll love it.
Step 1: Open up our existing MVC3 application in Visual Studio, that we created in the third part to interact with database with the help of Entity Framework.
Step 2: Create a folder named Repository and add an Interface to that folder named IUserRepository, this interface we derive from IDisposable type of interface.
We’ll declare methods for CRUD operations on User entity class over here, you can choose the names of the method as per your choice, but those should be easy to understand and follow.
Like I used in the below code of my interface:
using System;
using System.Collections.Generic;

namespace LearningMVC.Repository
{
public interface IUserRepository:IDisposable
{
IEnumerable GetUsers();
User GetUserByID(int userId);
void InsertUser(User user);
void DeleteUser(int userId);
void UpdateUser(User user);
void Save();
}
}

We can see each method name signifies particular CRUD operation on User entity.
User Entity is the same entity we generated in Model.tt class in Part3 of learning MVC, remember???????
Step 3: Extract a class from that interface and call it UserRepository. This UserRepository class will implement all the methods of that interface, but with the help of Entity Framework. Now here comes the use of our DBContextclass MVCEntities, we already have this class in our existing solution, so we don’t have to touch this class, simply, write our business logic in the interface methods implemented in UserRepository class:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace LearningMVC.Repository
{
public class UserRepository:IUserRepository
{
private MVCEntities context;

public UserRepository(MVCEntities context)
{
this.context = context;
}

public IEnumerable GetUsers()
{
return context.Users.ToList();
}

public User GetUserByID(int userId)
{
return context.Users.Find(userId);
}

public void InsertUser(User user)
{
context.Users.Add(user);
}

public void DeleteUser(int userId)
{
User user = context.Users.Find(userId);
context.Users.Remove(user);
}

public void UpdateUser(User user)
{
context.Entry(user).State = EntityState.Modified;
}

public void Save()
{
context.SaveChanges();
}

private bool disposed = false;

protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}

And inside the solution:

Interface

Class

90% of the job is done now. Now the only thing left is to use this repository in our controller.
This is needless to explain how you’ll call repository inside the controller, as you now know how to treat our controller, but still let’s do it for once.
Step 4: Go to the controller, declare the IUserRepository reference, and in the constructor initialize the object withUserRepository class, passing MVCEntities to the constructor as parameter we defined in UserRepositoryclass:
#region Private member variables...
private IUserRepository userRepository; 
#endregion

#region Public Constructor…
/// <summary>
/// Public Controller to initialize User Repository
/// </summary>
public MyController()
{
this.userRepository = new UserRepository(new MVCEntities());
}
#endregion

In the solution, this will look like:

Step 5: Now for all the actions of the controller in which we were using Entity Framework context directly, we replace the calling logic by the created userRepository object, and call methods defined in repository class.
Like, in Index controller, where we show the list of users, we do:
var userList = from user in userRepository.GetUsers() select user;
            var users = new List();
            if (userList.Any())
            {
                foreach (var user in userList)
                {
                    users.Add(new LearningMVC.Models.UserList() 
                    { UserId = user.UserId, Address = user.Address, 
                    Company = user.Company, FirstName = user.FirstName, 
                    LastName = user.LastName, Designation = user.Designation, 
                    EMail = user.EMail, PhoneNo = user.PhoneNo });
                }
            }

We can see the earlier code used remained the same, only a layer has been introduced between Entity Framework data access layer and business logic, and the controller now only uses that abstracted layer to communicate with database.

Similarly for other Actions of the controller:

Details

Create

Edit

Delete

Step 6: Run the application, and we see the application running as it was earlier:

Now that’s party time.

Conclusion

We now know how to make repositories too, and perform CRUD operations using it.
Now we can visualize how useful the pattern is and how it solved our issues of tight coupling and resulted in an appropriate architecture.
As per MSDN, Use the Repository pattern to achieve one or more of the following objectives:
  • You want to maximize the amount of code that can be tested with automation and to isolate the data layer to support unit testing.
  • You access the data source from many locations and want to apply centrally managed, consistent access rules and logic.
  • You want to implement and centralize a caching strategy for the data source.
  • You want to improve the code’s maintainability and readability by separating business logic from data or service access logic.
  • You want to use business entities that are strongly typed so that you can identify problems at compile time instead of at run time.
  • You want to associate a behavior with the related data. For example, you want to calculate fields or enforce complex relationships or business rules between the data elements within an entity.
  • You want to apply a domain model to simplify complex business logic.
And I fully agree to it, but has our application made use of the pattern appropriately? What if there are 100s of Repositories that need to be created? What if we have 100s of entities? Do we create Repositories for all of them, resulting in a mess and code redundancy? The answer is a big NO. In my next and last article of the series, we’ll learn how to create a Generic Repository to serve the purpose of n number of Entities. The source code of this article and existing article, i.e., Part 3 along with database scripts has been attached. You can download and run the solution, and drop me a question in case you feel like it. I’ll be happy to answer.

Read more:

Other Series

My other series of articles:

For more informative articles visit my Blog.

For more technical articles you can reach out to CodeTeddy.

Learning MVC Part 4 : Creating MVC Application with EntityFramework Code First Approach


Introduction

In our first three articles, we learnt a lot about MVC, starting from definition to use, from creating an application to connecting the MVC application with database using different techniques.
In the very last part of the series, we learnt how to connect our MVC application with existing database using Entity Framework.
This article will focus on connecting our MVC application with database using CodeFirst approach, i.e., one of the features Microsoft’s Entity Framework provides.

Our Roadmap

Just to remind our full roadmap towards learning MVC:
 

Pre-requisites

There are few pre-requisites before we start with the article:
  1. We have the running sample application that we created in the third part of the article series.
  2. We have EntityFramework 4.1 package or DLL on our local file system.
  3. We understand how MVC application is created.

Code-First Approach

To achieve a domain driven design, Entity Framework introduced EF 4.1 Code First. In the Code First approach, we focus on the domain design or entities/POCO classes first and create classes as per our model requirement. We do not have the database of the application, rather we create database automatically from code after defining our domain. The database created perfectly matches with the domain we design, so we have to be very conscious and keen in designing our domain model. It feels exciting to see database created on the fly with the help of our entities and XML configuration, without even opening database server.
No matter, you are not an expert in database, if you are a C# developer, just focus on your model/class creation.EntityFramework will take headache of creating and managing database for you.

Procedure

Step 1: Open the MVC application that we created in Learning MVC-Part3 in your Visual Studio.
We can clearly see and remember what we used to connect our MVC application to database with the help of entity framework, yes it was edmx class and our Model.tt classes generated from edmx classes.
Step 2: We don’t need the existing data-base, so you can delete the already created database for our part 3 application (if created).
Step 3: We don’t need edmx files now, so let’s clean our application, wipe out all these classes. Just deleteEFDataModel.edmxModel1.Context.tt and Model1.tt files. Now please do not run the application. It will give compile time errors, since we were using those classes ;-), Our solution will look like:
Our old solution had UserList class in Models folder, I have only changed the name of the class for differentiating it with previous application, and readability as was in the first part.
Step 4: As simple as that, just add a class to your solution, and name it MVCDBContext.cs as shown in the following image:
Step 5: Just add System.Data.Entity DLL as a reference to the solution if not already added.
Step 6: Use the namespace System.Data.Entity in our DBContext class, and inherit the added class fromDBContext class,
DbContext class: According to MSDN, DbContext class is conceptually similar to ObjectContext. To define, theObjectContext class is the part of the core EF API in the Microsoft .NET Framework 4 and this is our hero class that allows us to perform queries, change tracking and update the database using the strongly typed classes that represent our model (entity class). The DbContext is a wrapper around ObjectContext that exposes the most commonly used features of ObjectContext as well as provides some simpler “shortcuts” to tasks that are frequently used but complicated to code directly with ObjectContext. Simplfied alternative to ObjectContext and is the primary object for interacting with a database using a specific model.
Step 7: Add a DBSet property to the DbContext class that we created:
public DbSet Users { get; set; }
User, defined in angular brackets, is the model that we created in Models folder, so our MVCDBContext class looks like:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using LearningMVC.Models;

namespace LearningMVC
{
public class MVCDBContext : DbContext
{
public DbSet Users { get; set; }
}
}

That’s it, our 90% work is done?
DbSet property: It is a simplified alternative to ObjectSet and is used to perform CRUD operations against a specific type from the model.
By default, the name of the DbContext class will be the name our database that will automatically be created, so be wise to select the name of context class, else it could be handled in web.config as well.
The name of model will be the name of Table in database and properties of model will be the columns of the table.

Our Heroes

Both DbContext and DbSet are our super heroes, in creating and dealing with database operations, and make us far abstracted, providing ease of use to us.
When we are working with DbContext, we are in real working with entity sets. DbSet represents a typed entity set that is used to perform create, read, update, and delete operations. We are not creating DbSet objects and using them indepedently. DbSet can be only used with DbContext.
Step 8: Define a connection string in web.config file, you can remove previously defined connection string, the new connection string will somewhat look like:
The name of the connection string will be the name of the DbContect that we defined, i.e., MVCDbContext.
Step 9: Now, we just have to modify the access method in controllers, earlier, when we created application in third part, we were accessing the context class from the modelcontext class that was generated from edmx file. Edmx file was added having reference to already created database.
But now the case is different, we don’t have a database now, we’ll access the table and columns using ourMVCDBContext class in controllers, so just change the following line of code used in Actions of earlier application:
var dbContext = new MVCEntities() ;
to
var dbContext = new MVCDBContext();
Job done. 
Just Hit F5, and you’ll see:
How does the application run, where is the database??? Dude, go back to your database server, and check for database:
We see our database is created, with the name MVCDB, that’s the magic of EntityFramework. Now we can perform all the CRUD operations on this database, using our application. Just create a new user.
In database we see, user created.
By default, integer property with ID in its name of model will be the primary key in the database, in our caseUserId, or you can define the primary key in the model too.

Conclusion

Now we know how to play with EntityFramework to create database as per our domain model from our code, we have already moved ahead to advanced concepts of MVC and Entity Framework.
When we see the definition of DbContext, it uses the terms Repository Pattern and Unit of Work Pattern. We’ll discuss these more in detail in my next article.

Read more:

Other Series

My other series of articles:

For more informative articles visit my Blog.

For more technical articles you can reach out to CodeTeddy.

Code First Approach using Entity Framework 4.1, Inversion of Control, Unity Framework, Repository & Unit of Work Pattern and MVC3 Razor View


Download Source Code

Introduction :
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 an 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?
  • Do it require design patterns? If yes,What patterns should be implemented?
  • Should it be based on Seperation 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 Seperation 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 explaing 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 list of all added student.
The arcitecture is service based, following are the components and pictorial representation (fig1) of it, we’ll discuss each component in detail,
  1. CodeFirstData layer.
  2. CodeFirstEntities layer.
  3. CodeFirstServices layer.
  4. MVC Portal layer.


    Architecture components:

    Let’s discuss each and every component of the defined architecture in detail,
    1. 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.
    1. CodeFirstEntities layer:
    Entity layer acts as a model to MVC application,and also responsible for 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 osf the class in Dtaabase table.Primary key is either defined by the property named Id or “Classname[Id]”,in our case “StudentId”,this is default protocol set by entityframework to keep in mind while creating entities.Since this application is codefirest,we need to create entities first.
    1. 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 and do 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.
    1. MVCPortal layer:
    MVCPortal layer is our UI layer, it contains Model/ViewModels,Views and Controllers.I am not going into details of MVC as its not our primary target,I assume that you already know how to create and run MVC application,Lets have a quick revision of MVC,
      1. Model / Viewmodel:
    Model classea 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 lehp of views.
      1. Views :
    Views holds 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.
      1. Controllers :
    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 acces services instances,The IOC is acheived using global.asax file using UnityFramework library of Microsoft.
    5. Dlls : 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.
    Container :
    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() method instead of the “new” keyword.
    IService service = unityContainer.Resolve();
    I have added following references to acheive the same,
    Microsoft.Practices.Unity
    Microsoft.Practices.Unity.Configuration
    The code for IOC is implemented in global.asax file.
    Step by Step Process to create the Application using EntityFramework Architecture :
    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 databse by our own,we just write classes and defing connection configuration of our database server in web.config file, and let EntityFramework 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, that will act as a UI layer for our application. Refer fig2 for implementing the first step.


                                                                       ( fig2 )

    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,

                                                                                ( fig3 )

                                                                             ( 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.
    A. Create Context Class for Entity Framework :
    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.
                                                                (fig 5)


                                                                                   (fig 6)

    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 where TEntity is any POCO class. When we arerunning 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 ‘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.
    I ) DBInteractions :
    B. Generic Repository for EntityFramework Code First:
    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.


                            
                                                                            (fig 7)

    1. DataBase Factory:
    We have our database factory class defined as follows,


                                                                (fig 8)

                                                                     (fig 9)
    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.
    (fig 10)
    1. 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,
      Interface :


      Class :



      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.

      II ) Repository :
      In this article, we will be primarily focus on the persistence against Student entity . Let’s create a repository for handling CRUD operations for Student
      using derive from a generic Repository EntityRepositoryBase.
      Repository class for Student :
      Interface :

      Class :

       

    Step 4. 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 targetting CRUD operations, so the methods are quite simple in implementation,
    Interface :

     
    As we can see in abve interface the methods are to Get Student Details,List,Update and Delete Student.
    Class :
    usingSystem.Collections.Generic;
    usingCodeFirstData.DBInteractions;
    usingCodeFirstData.EntityRepositories;
    usingCodeFirstEntities;
    usingCodeFirstServices.Interfaces;
    namespaceCodeFirstServices.Services
    {
    publicclassStudentService: IStudentService
    {
    privatereadonlyIStudentRepository_studentRepository;
    privatereadonlyIUnitOfWork_unitOfWork;
    publicStudentService(IStudentRepositorystudentRepository, IUnitOfWorkunitOfWork)
    {
    this._studentRepository = studentRepository;
    this._unitOfWork = unitOfWork;
    }
    #regionIStudentService Members
    publicIEnumerable<Student> GetStudents()
    {
    varstudents = _studentRepository.GetAll();
    returnstudents;
    }
    publicStudentGetStudentById(intid)
    {
    varstudent = _studentRepository.GetById(id);
    returnstudent;
    }
    publicvoidCreateStudent(Studentstudent)
    {
    _studentRepository.Add(student);
    _unitOfWork.Commit();
    }
    publicvoidDeleteStudent(intid)
    {
    varstudent = _studentRepository.GetById(id);
    _studentRepository.Delete(student);
    _unitOfWork.Commit();
    }
    publicvoidUpdateStudent(Studentstudent)
    {
    _studentRepository.Update(student);
    _unitOfWork.Commit();
    }
    publicvoidSaveStudent()
    {
    _unitOfWork.Commit();
    }
    #endregion
    }
    }
    Class uses refernces of Repositories and Entities, and Dependency of Repositories is resolved in Constructor of the service itself.
    Step 5. The MVC Portal :
    Before we start MVC portal,Lets 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.
    publicclassHttpContextLifetimeManager : LifetimeManager, IDisposable
    {
    publicoverrideobjectGetValue()
    {
    varassemblyQualifiedName = typeof(T).AssemblyQualifiedName;
    if(assemblyQualifiedName != null)
    returnHttpContext.Current.Items[assemblyQualifiedName];
    returnnull;
    }
    publicoverridevoidRemoveValue()
    {
    varassemblyQualifiedName = typeof(T).AssemblyQualifiedName;
    if(assemblyQualifiedName != null)
    HttpContext.Current.Items.Remove(assemblyQualifiedName);
    }
    publicoverridevoidSetValue(objectnewValue)
    {
    varassemblyQualifiedName = typeof(T).AssemblyQualifiedName;
    if(assemblyQualifiedName != null)
    HttpContext.Current.Items[assemblyQualifiedName] = newValue;
    }
    publicvoidDispose()
    {
    RemoveValue();
    }
    }
    }
    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 intreface
    usingSystem;
    usingSystem.Web.Mvc;
    namespaceCodeFirstPortal.IoC
    {
    publicclassCustomControllerActivator: IControllerActivator
    {
    IControllerIControllerActivator.Create(
    System.Web.Routing.RequestContextrequestContext,
    TypecontrollerType){
    returnDependencyResolver.Current
    .GetService(controllerType) asIController;
    }
    }
    }
    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 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.
    usingSystem;
    usingSystem.Web;
    usingSystem.Web.Mvc;
    usingSystem.Web.Routing;
    usingMicrosoft.Practices.Unity;
    namespaceCodeFirstPortal.IoC
    {
    publicclassUnityControllerFactory: DefaultControllerFactory
    {
    IUnityContainercontainer;
    publicUnityControllerFactory(IUnityContainercontainer)
    {
    this.container = container;
    }
    protectedoverrideIControllerGetControllerInstance(RequestContextreqContext, TypecontrollerType)
    {
    IControllercontroller;
    if(controllerType == null)
    thrownewHttpException(
    404, String.Format(
    “The controller for ‘{0}‘ could not be found”+ “or it does not implement IController.”,
    reqContext.HttpContext.Request.Path));
    if(!typeof(IController).IsAssignableFrom(controllerType))
    thrownewArgumentException(
    string.Format(
    “Requested type is not a controller: {0},
    controllerType.Name),
    “controllerType”);
    try
    {
    controller= container.Resolve(controllerType) asIController;
    }
    catch(Exceptionex)
    {
    thrownewInvalidOperationException(String.Format(
    “Error resolving the controller {0},
    controllerType.Name), ex);
    }
    returncontroller;
    }
    }
    Resolving Service Dependency :
    usingSystem;
    usingSystem.Collections.Generic;
    usingSystem.Web.Mvc;
    usingMicrosoft.Practices.Unity;
    namespaceCodeFirstPortal.IoC
    {
    publicclassUnityDependencyResolver: IDependencyResolver
    {
    IUnityContainercontainer;
    publicUnityDependencyResolver(IUnityContainercontainer)
    {
    this.container = container;
    }
    publicobjectGetService(TypeserviceType)
    {
    try
    {
    returncontainer.Resolve(serviceType);
    }
    catch
    {
    returnnull;
    }
    }
    publicIEnumerable<object> GetServices(TypeserviceType)
    {
    try
    {
    returncontainer.ResolveAll(serviceType);
    }
    catch
    {
    returnnewList<object>();
    }
    }
    }
    }
    global.asax :
    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.
    usingSystem.Web.Mvc;
    usingSystem.Web.Routing;
    usingCodeFirstData.DBInteractions;
    usingCodeFirstData.EntityRepositories;
    usingCodeFirstPortal.IoC;
    usingCodeFirstServices.Interfaces;
    usingCodeFirstServices.Services;
    usingMicrosoft.Practices.Unity;
    namespaceMvcPortal
    {
    publicclassMvcApplication: System.Web.HttpApplication
    {
    publicstaticvoidRegisterGlobalFilters(GlobalFilterCollectionfilters)
    {
    filters.Add(newHandleErrorAttribute());
    }
    publicstaticvoidRegisterRoutes(RouteCollectionroutes)
    {
    routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
    routes.MapRoute(
    “Default”, // Route name
    “{controller}/{action}/{id}”, // URL with parameters
    new{ controller = “Home”, action = “Index”, id = UrlParameter.Optional } // Parameter defaults
    );
    }
    protectedvoidApplication_Start()
    {
    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    IUnityContainercontainer = GetUnityContainer();
    DependencyResolver.SetResolver(newUnityDependencyResolver(container));
    }
    privateIUnityContainerGetUnityContainer()
    {
    //Create UnityContainer
    IUnityContainercontainer = newUnityContainer()
    .RegisterType<IDBFactory, DBFactory>(newHttpContextLifetimeManager<IDBFactory>())
    .RegisterType<IUnitOfWork, UnitOfWork>(newHttpContextLifetimeManager<IUnitOfWork>())
    .RegisterType<IStudentService, StudentService>(newHttpContextLifetimeManager<IStudentService>())
    .RegisterType<IStudentRepository, StudentRepository>(newHttpContextLifetimeManager<IStudentRepository>());
    returncontainer;
    }
    }
    }
    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 :
    1. 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 listy 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 acheiving our objective.
    1. We create Student Controller, We define actions in the controller for each operation we want to perform as follows,
    usingSystem;
    usingSystem.Linq;
    usingSystem.Web.Mvc;
    usingCodeFirstEntities;
    usingCodeFirstServices.Interfaces;
    namespaceCodeFirstPortal.Controllers
    {
    publicclassStudentController: Controller
    {
    privatereadonlyIStudentService_studentService;
    publicStudentController(IStudentServicestudentService)
    {
    this._studentService = studentService;
    }
    [HttpGet]
    publicActionResultDetails(int? id)
    {
    varstudentDetails = _studentService.GetStudentById((int) id);
    if(studentDetails == null) thrownewArgumentNullException(“Not Found”);
    returnView(studentDetails);
    }
    [HttpGet]
    publicActionResultDelete(int? id)
    {
    varstudentDetails = _studentService.GetStudentById((int) id);
    if(studentDetails == null) thrownewArgumentNullException(“Not Found”);
    returnView(studentDetails);
    }
    [HttpPost]
    publicActionResultDelete(Studentstudent)
    {
    _studentService.DeleteStudent(student.StudentId);
    returnRedirectToAction(“List”, “Student”);
    }
    [HttpGet]
    publicActionResultEdit(int? id)
    {
    varstudentDetails = _studentService.GetStudentById((int) id);
    if(studentDetails == null) thrownewArgumentNullException(“Not Found”);
    returnView(studentDetails);
    }
    [HttpPost]
    publicActionResultEdit(Studentstudent)
    {
    _studentService.UpdateStudent(student);
    returnRedirectToAction(“List”, “Student”);
    }
    [HttpGet]
    publicActionResultCreate()
    {
    returnView();
    }
    [HttpPost]
    publicActionResultCreate(Studentstudent)
    {
    varstudentModel = newStudent()
    {
    Address = student.Address,
    Country = student.Country,
    Name = student.Name,
    Age = student.Age,
    Email = student.Email
    };
    _studentService.CreateStudent(studentModel);
    returnRedirectToAction(“List”, “Student”);
    }
    [HttpGet]
    publicActionResultList()
    {
    varstudents = _studentService.GetStudents();
    if(students.Any())
    {
    returnView(“List”, students);
    }
    returnView(“List”);
    }
    }
    }
    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.
    1. We Create Views for every Action,Its 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,
      4. 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,U can customize the same.When u 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 dont have existing list, and our application shows,



      1. No wonder , just have a look at your DataBase, My case I am using Sql Server 2008,


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

        1. Further Operations :
        You can now test the application and perform further CRUD operations in the application and see the DataBase getting updated.e.g. Create Student,


        after Submit by pressing Create, we get,


        therefore one student created.

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


        Likewise we can see the details of already created student,


        and delete the student will redirect to ,


        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 SetInitializer method of DataBase class and set it to null in our dataBase Factory Class.

        usingSystem.Data.Entity;
        namespaceCodeFirstData.DBInteractions
        {
        publicclassDBFactory: Disposable, IDBFactory
        {
        publicDBFactory()
        {
        Database.SetInitializer<CodeFirstContext>(null);
        }
        privateCodeFirstContextdataContext;
        publicCodeFirstContextGet()
        {
        returndataContext ?? (dataContext = newCodeFirstContext());
        }
        protectedoverridevoidDisposeCore()
        {
        if(dataContext != null)
        dataContext.Dispose();
        }
        }
        }
        Database class is from namespace System.Data.Entity, whcih provides such feature.
        Conclusion :
        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 acheive 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.

        Articles : http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=7869570