Developing web apps using ASP.NET MVC 3, Razor and EF Code First - Part 1

Posted by shiju on ASP.net Weblogs See other posts from ASP.net Weblogs or by shiju
Published on Thu, 06 Jan 2011 11:37:57 GMT Indexed on 2011/01/06 11:54 UTC
Read the original article Hit count: 538

In this post, I will demonstrate web application development using ASP. NET MVC 3, Razor and EF code First. This post will also cover Dependency Injection using Unity 2.0 and generic Repository and Unit of Work for EF Code First. The following frameworks will be used for this step by step tutorial.

  1. ASP.NET MVC 3
  2. EF Code First CTP 5
  3. Unity 2.0


Define Domain Model


Let’s create domain model for our simple web application

Category class

  1. public class Category
  2. {
  3.     public int CategoryId { get; set; }
  4.     [Required(ErrorMessage = "Name Required")]
  5.     [StringLength(25, ErrorMessage = "Must be less than 25 characters")]
  6.     public string Name { get; set;}
  7.     public string Description { get; set; }
  8.     public virtual ICollection<Expense> Expenses { get; set; }
  9. }

 

Expense class

  1. public class Expense
  2. {
  3.        
  4.     public int ExpenseId { get; set; }       
  5.     public string  Transaction { get; set; }
  6.     public DateTime Date { get; set; }
  7.     public double Amount { get; set; }
  8.     public int CategoryId { get; set; }
  9.     public virtual Category Category { get; set; }
  10. }


We have two domain entities - Category and Expense. A single category contains a list of expense transactions and every expense transaction should have a Category. In this post, we will be focusing on CRUD operations for the entity Category and will be working on the Expense entity with a View Model object in the later post. And the source code for this application will be refactored over time.


The above entities are very simple POCO (Plain Old CLR Object) classes and the entity Category 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. EF Code First is reached CTP 5 when I am writing this article.


Creating Context Class for Entity Framework


We have created our domain model and let’s create a class in order to working with Entity Framework Code First. For this, you have to download EF Code First CTP 5 and add reference to the assembly EntitFramework.dll. You can also use NuGet to download add reference to EEF Code First. 

 

  1. public class MyFinanceContext : DbContext
  2. {
  3.     public MyFinanceContext() : base("MyFinance") { }
  4.     public DbSet<Category> Categories { get; set; }
  5.     public DbSet<Expense> Expenses { get; set; }        
  6. }

 

The above class MyFinanceContext is derived from DbContext that can connect your model classes to a database. The MyFinanceContext class is mapping our Category and Expense class into database tables
Categories and Expenses using DbSet<TEntity> where TEntity is any POCO class. When we are running the application at first time, it will automatically create the database. EF code-first look for a connection string in web.config or app.config that has the same name as the dbcontext class. If it is not find any connection string with the convention, it will automatically create database in local SQL Express database by default and the name of the database will be same name as the dbcontext class. You can also define the name of database in constructor of the the dbcontext class.


Unlike NHibernate, we don’t have to use any XML based mapping files or Fluent interface for mapping between our model and database. 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 ‘<class name>Id’.  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.


Generic Repository for EF Code First


We have created model classes and dbcontext class. Now we have to create generic repository pattern for data persistence with EF code first. If you don’t know about the repository pattern, checkout Martin Fowler’s article on Repository

Let’s create a generic repository to working with DbContext and DbSet generics.

  1. public interface IRepository<T> where T : class
  2.     {
  3.         void Add(T entity);
  4.         void Delete(T entity);
  5.         T GetById(long Id);
  6.         IEnumerable<T> All();
  7.     }

 

RepositoryBasse – Generic Repository class

  1. public abstract class RepositoryBase<T> where T : class
  2. {
  3. private MyFinanceContext database;
  4. private readonly IDbSet<T> dbset;
  5. protected RepositoryBase(IDatabaseFactory databaseFactory)
  6. {
  7.     DatabaseFactory = databaseFactory;
  8.     dbset = Database.Set<T>();
  9. }
  10.  
  11. protected IDatabaseFactory DatabaseFactory
  12. {
  13.     get; private set;
  14. }
  15.  
  16. protected MyFinanceContext Database
  17. {
  18.     get { return database ?? (database = DatabaseFactory.Get()); }
  19. }
  20. public virtual void Add(T entity)
  21. {
  22.     dbset.Add(entity);           
  23. }
  24.       
  25. public virtual void Delete(T entity)
  26. {
  27.     dbset.Remove(entity);
  28. }
  29.  
  30. public virtual T GetById(long id)
  31. {
  32.     return dbset.Find(id);
  33. }
  34.  
  35. public virtual IEnumerable<T> All()
  36. {
  37.     return dbset.ToList();
  38. }
  39. }

 

DatabaseFactory class

  1. public class DatabaseFactory : Disposable, IDatabaseFactory
  2. {
  3.     private MyFinanceContext database;
  4.     public MyFinanceContext Get()
  5.     {
  6.         return database ?? (database = new MyFinanceContext());
  7.     }
  8.     protected override void DisposeCore()
  9.     {
  10.         if (database != null)
  11.             database.Dispose();
  12.     }
  13. }

Unit of Work


If you are new to Unit of Work pattern, checkout Fowler’s article on Unit of Work . According to Martin Fowler, 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."


Let’s create a class for handling Unit of Work

 

  1. public interface IUnitOfWork
  2. {
  3.     void Commit();
  4. }

 

UniOfWork class

  1. public class UnitOfWork : IUnitOfWork
  2. {
  3.     private readonly IDatabaseFactory databaseFactory;
  4.     private MyFinanceContext dataContext;
  5.  
  6.     public UnitOfWork(IDatabaseFactory databaseFactory)
  7.     {
  8.         this.databaseFactory = databaseFactory;
  9.     }
  10.  
  11.     protected MyFinanceContext DataContext
  12.     {
  13.         get { return dataContext ?? (dataContext = databaseFactory.Get()); }
  14.     }
  15.  
  16.     public void Commit()
  17.     {
  18.         DataContext.Commit();
  19.     }
  20. }

 


The Commit method of the UnitOfWork will call the commit method of MyFinanceContext class and it will execute the SaveChanges method of DbContext class.
 
Repository class for Category

In this post, we will be focusing on the persistence against Category entity and will working on other entities in later post. Let’s create a repository for handling CRUD operations for Category using derive from a generic Repository RepositoryBase<T>.

 

  1. public class CategoryRepository: RepositoryBase<Category>, ICategoryRepository
  2.     {
  3.     public CategoryRepository(IDatabaseFactory databaseFactory)
  4.         : base(databaseFactory)
  5.         {
  6.         }           
  7.     }
  8. public interface ICategoryRepository : IRepository<Category>
  9. {
  10. }


If we need additional methods than generic repository for the Category, we can define in the CategoryRepository.


Dependency Injection using Unity 2.0


If you are new to Inversion of Control/ Dependency Injection or Unity, please have a look on my articles at http://weblogs.asp.net/shijuvarghese/archive/tags/IoC/default.aspx. I want to create a custom lifetime manager for Unity to store container in the current HttpContext.

 

  1. public class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable
  2. {
  3.     public override object GetValue()
  4.     {
  5.         return HttpContext.Current.Items[typeof(T).AssemblyQualifiedName];
  6.     }
  7.     public override void RemoveValue()
  8.     {
  9.         HttpContext.Current.Items.Remove(typeof(T).AssemblyQualifiedName);
  10.     }
  11.     public override void SetValue(object newValue)
  12.     {
  13.         HttpContext.Current.Items[typeof(T).AssemblyQualifiedName] = newValue;
  14.     }
  15.     public void Dispose()
  16.     {
  17.         RemoveValue();
  18.     }
  19. }

 

Let’s create controller factory for Unity in the ASP.NET MVC 3 application.

  1. public class UnityControllerFactory : DefaultControllerFactory
  2. {
  3. IUnityContainer container;
  4. public UnityControllerFactory(IUnityContainer container)
  5. {
  6.     this.container = container;
  7. }
  8. protected override IController GetControllerInstance(RequestContext reqContext, Type controllerType)
  9. {
  10.     IController controller;
  11.     if (controllerType == null)
  12.         throw new HttpException(
  13.                 404, String.Format(
  14.                     "The controller for path '{0}' could not be found" +
  15.     "or it does not implement IController.",
  16.                 reqContext.HttpContext.Request.Path));
  17.  
  18.     if (!typeof(IController).IsAssignableFrom(controllerType))
  19.         throw new ArgumentException(
  20.                 string.Format(
  21.                     "Type requested is not a controller: {0}",
  22.                     controllerType.Name),
  23.                     "controllerType");
  24.     try
  25.     {
  26.         controller= container.Resolve(controllerType) as IController;
  27.     }
  28.     catch (Exception ex)
  29.     {
  30.         throw new InvalidOperationException(String.Format(
  31.                                 "Error resolving controller {0}",
  32.                                 controllerType.Name), ex);
  33.     }
  34.     return controller;
  35. }
  36.  
  37. }

 

Configure contract and concrete types in Unity

Let’s configure our contract and concrete types in Unity for resolving our dependencies.

 

  1. private void ConfigureUnity()
  2. {
  3.     //Create UnityContainer          
  4.     IUnityContainer container = new UnityContainer()            
  5.     .RegisterType<IDatabaseFactory, DatabaseFactory>(new HttpContextLifetimeManager<IDatabaseFactory>())
  6.     .RegisterType<IUnitOfWork, UnitOfWork>(new HttpContextLifetimeManager<IUnitOfWork>())
  7.     .RegisterType<ICategoryRepository, CategoryRepository>(new HttpContextLifetimeManager<ICategoryRepository>());            
  8.     //Set container for Controller Factory           
  9.     ControllerBuilder.Current.SetControllerFactory(
  10.             new UnityControllerFactory(container));
  11. }

 

In the above ConfigureUnity method, we are registering our types onto Unity container with custom lifetime manager HttpContextLifetimeManager. Let’s call ConfigureUnity method in the Global.asax.cs for set controller factory for Unity and configuring the types with Unity.

 

  1. protected void Application_Start()
  2. {
  3.     AreaRegistration.RegisterAllAreas();
  4.     RegisterGlobalFilters(GlobalFilters.Filters);
  5.     RegisterRoutes(RouteTable.Routes);
  6.     ConfigureUnity();
  7. }

 

Developing web application using ASP.NET MVC 3

We have created our domain model for our web application and also have created repositories and configured dependencies with Unity container. Now we have to create controller classes and views for doing CRUD operations against the Category entity.


Let’s create controller class for Category

Category Controller

 

  1. public class CategoryController : Controller
  2. {
  3.     private readonly ICategoryRepository categoryRepository;
  4.     private readonly IUnitOfWork unitOfWork;
  5.  
  6.         public CategoryController(ICategoryRepository categoryRepository, IUnitOfWork unitOfWork)
  7.     {
  8.         this.categoryRepository = categoryRepository;
  9.         this.unitOfWork = unitOfWork;
  10.     }  
  11.     public ActionResult Index()
  12.     {
  13.         var categories = categoryRepository.All();
  14.         return View(categories);
  15.     }
  16.     [HttpGet]
  17.     public ActionResult Edit(int id)
  18.     {
  19.         var category = categoryRepository.GetById(id);
  20.         return View(category);
  21.     }
  22.  
  23.     [HttpPost]
  24.     public ActionResult Edit(int id, FormCollection collection)
  25.     {
  26.         var category = categoryRepository.GetById(id);
  27.         if (TryUpdateModel(category))
  28.         {
  29.             unitOfWork.Commit();
  30.             return RedirectToAction("Index");
  31.         }
  32.         else return View(category);            
  33.     }
  34.  
  35.     [HttpGet]
  36.     public ActionResult Create()
  37.     {
  38.         var category = new Category();
  39.         return View(category);
  40.     }
  41.      
  42.     [HttpPost]
  43.     public ActionResult Create(Category category)
  44.     {
  45.         if (!ModelState.IsValid)
  46.         {
  47.             return View("Create", category);
  48.         }            
  49.         categoryRepository.Add(category);
  50.         unitOfWork.Commit();
  51.         return RedirectToAction("Index");
  52.     }
  53.  
  54.     [HttpPost]
  55.     public ActionResult Delete(int  id)
  56.     {
  57.         var category = categoryRepository.GetById(id);
  58.         categoryRepository.Delete(category);
  59.         unitOfWork.Commit();
  60.         var categories = categoryRepository.All();
  61.         return PartialView("CategoryList", categories);
  62.  
  63.     }       
  64. }

 

Creating Views in Razor

Now we are going to create views in Razor for our ASP.NET MVC 3 application.  Let’s create a partial view CategoryList.cshtml for listing category information and providing link for Edit and Delete operations.

CategoryList.cshtml

  1. @using MyFinance.Helpers;
  2. @using MyFinance.Domain;
  3. @model IEnumerable<Category>   
  4.   <table>
  5.         <tr>
  6.         <th>Actions</th>
  7.         <th>Name</th>
  8.          <th>Description</th>
  9.         </tr>
  10.     @foreach (var item in Model) {    
  11.         <tr>
  12.             <td>
  13.                 @Html.ActionLink("Edit", "Edit",new { id = item.CategoryId })
  14.                 @Ajax.ActionLink("Delete", "Delete", new { id = item.CategoryId }, new AjaxOptions { Confirm = "Delete Expense?", HttpMethod = "Post", UpdateTargetId = "divCategoryList" })              
  15.             </td>
  16.             <td>
  17.                 @item.Name
  18.             </td>
  19.             <td>
  20.                 @item.Description
  21.             </td>
  22.         </tr>
  23.     
  24.     }
  25.  
  26.     </table>
  27.     <p>
  28.         @Html.ActionLink("Create New", "Create")
  29.     </p>

The delete link is providing Ajax functionality using the Ajax.ActionLink. This will call an Ajax request for Delete action method in the CategoryCotroller class. In the Delete action method, it will return Partial View CategoryList after deleting the record. We are using CategoryList view for the Ajax functionality and also for Index view using for displaying list of category information.

Let’s create Index view using partial view CategoryList 

Index.chtml

  1. @model IEnumerable<MyFinance.Domain.Category>
  2. @{
  3.     ViewBag.Title = "Index";
  4. }
  5.    <h2>Category List</h2>
  6.    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
  7.    <div id="divCategoryList">          
  8.     @Html.Partial("CategoryList", Model)
  9. </div>

 

We can call the partial views using Html.Partial helper method. Now we are going to create View pages for insert and update functionality for the Category.

Both view pages are sharing common user interface for entering the category information. So I want to create an EditorTemplate for the Category information. We have to create the EditorTemplate with the same name of entity object so that we can refer it on view pages using @Html.EditorFor(model => model) . So let’s create template with name Category.


Let’s create view page for insert Category information

 

  1. @model MyFinance.Domain.Category
  2.  
  3. @{
  4.     ViewBag.Title = "Save";
  5. }
  6.  
  7. <h2>Create</h2>
  8.  
  9. <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
  10. <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
  11.  
  12. @using (Html.BeginForm()) {
  13.     @Html.ValidationSummary(true)
  14.     <fieldset>
  15.         <legend>Category</legend>
  16.                @Html.EditorFor(model => model)      
  17.         <p>
  18.             <input type="submit" value="Create" />
  19.         </p>
  20.     </fieldset>
  21. }
  22.  
  23. <div>
  24.     @Html.ActionLink("Back to List", "Index")
  25. </div>

ViewStart file


In Razor views, we can add a file named _viewstart.cshtml in the views directory  and this will be shared among the all views with in the Views directory. The below code in the _viewstart.cshtml, sets the Layout page for every Views in the Views folder.     

  1. @{
  2.     Layout = "~/Views/Shared/_Layout.cshtml";
  3. }

 

Source Code

You can download the source code from http://efmvc.codeplex.com/ . The source will be refactored on over time.

 

Summary

In this post, we have created a simple web application using ASP.NET MVC 3 and EF Code First. We have discussed on technologies and practices such as ASP.NET MVC 3, Razor, EF Code First, Unity 2, generic Repository and Unit of Work. In my later posts, I will modify the application and will be discussed on more things. Stay tuned to my blog  for more posts on step by step application building.

© ASP.net Weblogs or respective owner

Related posts about ASP.NET

Related posts about ASP.NET MVC