CRUD Operations Using Entity Framework 5.0 Code First Approach in MVC

Introduction

This article introduces the Entity Framework 5.0 Code First approach in MVC applications. We are developing an application for Publisher and Book entities on which we can perform Create, Read, Update and Delete operations. We create these two entities and make a one-to-many relationship between them using the Fluent API.

The ADO.NET Entity Framework is an Object Relational Mapper (ORM) included with the .NET framework. It basically generates business objects and entities according to the database tables. It provides basic CRUD operations, easily managing relationships among entities with the ability to have an inheritance relationship among entities.

When using the EF we interact with an entity model instead of the application's relational database model. This abstraction allows us to focus on business behavior and the relationships among entities. We use the Entity Framework data context to perform queries. When one of the CRUD operations is invoked, the Entity Framework will generate the necessary SQL to perform the operation.

Background

To create this application we should have a basic knowledge of the DbContext class of the System.Data.Entity namespace. We should also be familiar with views because in this article I am not describing views for each action method so you can create a view according to action methods or you can scaffold templates to create a view for Edit, List, Create, Delete and Details.

We need to install the Entity Framework Nuget package in our application. When we install the Entity Framework Nuget package, two references (System.Data.Entity and EntityFramework) are added to our application. Thereafter we can perform CRUD operations using Entity Framework.

image1.gif
Figure 1.1 Install Entity Framework Nuget Package

Entity Framework Code First Approach

Whether you have an existing database or not, you can code your own classes and properties (aka Plain Old CLR Objects, or POCOs) that correspond to tables and columns and use them with the Entity Framework without an .edmx file. In this approach the Entity Framework does not leverage any kind of configuration file (.edmx file) to store the database schema, because the mapping API uses these conventions to generate the database schema dynamically at runtime. Currently, the Entity Framework Code First approach does not support mapping to Stored Procedures. The ExecuteSqlCommand() and SqlQuery() methods can be used to execute Stored Procedures.

To understand the Entity Framework Code First Approach, you need to create an MVC application that has two entities, one is Publisher and another is Book. So let's see an example step-by-step.

To create your MVC Application, in Visual Studio select "File" -> "New" -> "Project..." then select "MVC 4 Application" then select "Empty Application".

Create Model Classes

We create classes for Publisher and Book under the Models folder, those classes are used as entities and an entities set. These classes will have mapping with a database because we are using the code first approach and these classes will create a table in a database using the DbContext class of Entity Framework. So let's see these classes one by one.

The Publisher Class is in the Models folder; that filename is Publisher.cs as in the following:
  1. using System.Collections.Generic;   
  2. namespace ExampleCodeFirstApproch.Models  
  3. {  
  4.     public class Publisher  
  5.     {  
  6.         public int PublisherId { getset; }  
  7.         public string PublisherName { getset; }  
  8.         public string Address { getset; }  
  9.         public ICollection<Book> Books { getset; }  
  10.     }  
  11. }
The Book Class is in the Models folder; that filename is Book.cs as in the following:
  1. namespace ExampleCodeFirstApproch.Models  
  2. {  
  3.     public class Book  
  4.     {  
  5.         public int BookId { getset; }  
  6.         public string Title { getset; }  
  7.         public string Year { getset; }  
  8.         public int PublisherId { getset; }  
  9.         public Publisher Publisher { getset; }  
  10.     }  
  11. }
Create Data Access Layer

This part of the article is the heart of the article as well as the code first approach. First of all we need a connection string so we can connect with our database by application. We create a connection in the web.config file. I provide the connection string name as DbConnectionString, you are free to give any name to it but remember it because we will use it in our context class.
  1. <connectionStrings>     
  2.     <add name="DbConnectionString" connectionString="Data Source=sandeepss-PC;Initial Catalog=CodeFirst;User ID=sa; Password=*******" providerName="System.Data.SqlClient" />  
  3. </connectionStrings>  

We have both classes, Publisher and Book, so now we will create a context class. We create a LibraryContext class under the Models folder, that file name is LibraryContext.cs. This class inherits DbContext so we can use the DbContext class methods using a LibraryContext class object as in the following:

  1. using System.ComponentModel.DataAnnotations.Schema;  
  2. using System.Data.Entity;   
  3. namespace ExampleCodeFirstApproch.Models  
  4. {  
  5.     public class LibraryContext :DbContext  
  6.     {  
  7.         public LibraryContext()  
  8.             : base("name=DbConnectionString")  
  9.         {  
  10.         }   
  11.         public DbSet<Publisher> Publishers { getset; }  
  12.         public DbSet<Book> Books { getset; }   
  13.         protected override void OnModelCreating(DbModelBuilder modelBuilder)  
  14.         {                       
  15.             modelBuilder.Entity<Publisher>().HasKey(p => p.PublisherId);  
  16.             modelBuilder.Entity<Publisher>().Property(c => c.PublisherId)  
  17.                 .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);             
  18.             modelBuilder.Entity<Book>().HasKey(b => b.BookId);  
  19.             modelBuilder.Entity<Book>().Property(b => b.BookId)  
  20.                 .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);             
  21.             modelBuilder.Entity<Book>().HasRequired(p => p.Publisher)  
  22.                 .WithMany(b => b.Books).HasForeignKey(b=>b.PublisherId);             
  23.             base.OnModelCreating(modelBuilder);  
  24.         }  
  25.     }  
  26. }
Our LibraryContext class that inherits the DbContext class is ready. The LibraryContext class has a three-part constructor, DbSet properties, OnModelCreating method. Let's see each one by one.

Constructor : It is an empty constructor that doesn't have any parameters, in other words it is the default constructor but it inherits the base class single string parameterized constructor. This constructor constructs a new context instance using the given string as the name (as we used) or the connection string for the database to which a connection will be made. Here DbConnectionString is the name of the connection string defined in the web.config file of the application.
  1. public LibraryContext(): base("name=DbConnectionString")  
  2. {  
  3. }
Property: When developing with the Code First workflow you define a derived DbContext that represents the session with the database and exposes a DbSet for each type in your model. The common case shown in the Code First examples is to have a DbContext with public automatic DbSet properties for the entity types of your model.
  1. public DbSet<Publisher> Publishers { getset; }  
  2. public DbSet<Book> Books { getset; }
The Dbset property represents an entity set used to perform create, read, update, and delete operations. A non-generic version of DbSet<TEntity> can be used when the type of entity is not known at build time. Here we are using the plural name of the property for an entity, that means your table will be created with this name in the database for that specific entity.

Method: The LibraryContext class has an override OnModelCreating method. This method is called when the model for a derived context has been initialized, but before the model has been locked down and used to initialize the context. The default implementation of this method does nothing, but it can be overridden in a derived class such that the model can be further configured before it is locked down. Basically in this method we configure the database table that will be created by a model or a defined relationship among those tables.
  1. protected override void OnModelCreating(DbModelBuilder modelBuilder)  
  2. {    
  3.     modelBuilder.Entity<Publisher>().HasKey(p => p.PublisherId);  
  4.     modelBuilder.Entity<Publisher>().Property(c => c.PublisherId)  
  5.               .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);             
  6.     modelBuilder.Entity<Book>().HasKey(b => b.BookId);  
  7.     modelBuilder.Entity<Book>().Property(b => b.BookId)  
  8.              .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);             
  9.     modelBuilder.Entity<Book>().HasRequired(p => p.Publisher)  
  10.              .WithMany(b => b.Books).HasForeignKey(b=>b.PublisherId);             
  11.     base.OnModelCreating(modelBuilder);  
  12. }
This method accepts one parameter, an object of DbModelBuilder. This DbModelBuilder class maps POCO classes to database schema. This method is called only once when the first instance of a derived context is created. The model for that context is then cached and is for all further instances of the context in the app domain. This caching can be disabled by setting the ModelCaching property on the given ModelBuidler, but this can seriously degrade performance. More control over caching is provided through use of the DbModelBuilder and DbContext classes directly.

Configure/Mapping Properties with the Fluent API

The OnModelCreating() method under the LibraryContext class uses the Fluent API to map and configure properties in the table. So let's see each method used in the OnModelCreating() method one by one.

  1. HasKey() : The Haskey() method configures a primary key on table.
  2. Property() : The Property method configures attributes for each property belonging to an entity or complex type. It is used to obtain a configuration object for a given property. The options on the configuration object are specific to the type being configured; IsUnicode is available only on string properties for example.
  3. HasDatabaseGeneratedOption : It configures how values for the property are generated by the database.
  4. DatabaseGeneratedOption.Identity : DatabaseGeneratedOption is database annotation. It enumerates a database generated option. DatabaseGeneratedOption.Identity is used to create an auto-increment column in the table by unique value.
  5. The foreign key relation is defined between Publisher and the Book using the following expression:
    modelBuilder.Entity<Book>().HasRequired(p => p.Publisher)
    .WithMany(b => b.Books).HasForeignKey(b=>b.PublisherId);

Create Controller for CRUD Operations

Now we create two controllers, one for Publisher CRUD operations (PublisherController.cs) and another for Book CRUD operations (BookController.cs) under the Controllers folder in the application. So here is the code for each.

The Publisher controller in the file PublisherController.cs in the Controllers folder:

  1. using System.Linq;  
  2. using System.Web.Mvc;  
  3. using ExampleCodeFirstApproch.Models;   
  4. namespace ExampleCodeFirstApproch.Controllers  
  5. {  
  6.     public class PublisherController : Controller  
  7.     {  
  8.         LibraryContext objContext;  
  9.         public PublisherController()  
  10.         {  
  11.             objContext = new LibraryContext();  
  12.         }   
  13.         #region List and Details Publisher   
  14.         public ActionResult Index()  
  15.         {  
  16.             var publishers = objContext.Publishers.ToList();  
  17.             return View(publishers);  
  18.         }   
  19.         public ViewResult Details(int id)  
  20.         {  
  21.             Publisher publisher = objContext.Publishers.Where(x=>x.PublisherId==id).SingleOrDefault();  
  22.             return View(publisher);  
  23.         }   
  24.         #endregion   
  25.         #region Create Publisher   
  26.         public ActionResult Create()  
  27.         {  
  28.             return View(new Publisher());  
  29.         }   
  30.         [HttpPost]  
  31.         public ActionResult Create(Publisher publish)  
  32.         {  
  33.             objContext.Publishers.Add(publish);  
  34.             objContext.SaveChanges();  
  35.             return RedirectToAction("Index");  
  36.         }   
  37.         #endregion   
  38.         #region edit publisher   
  39.         public ActionResult Edit(int id)  
  40.         {  
  41.             Publisher publisher = objContext.Publishers.Where(x => x.PublisherId == id).SingleOrDefault();  
  42.             return View(publisher);  
  43.         }   
  44.         [HttpPost]  
  45.         public ActionResult Edit(Publisher model)  
  46.         {  
  47.             Publisher publisher = objContext.Publishers.Where(x => x.PublisherId == model.PublisherId).SingleOrDefault();  
  48.             if (publisher != null)  
  49.             {  
  50.                 objContext.Entry(publisher).CurrentValues.SetValues(model);  
  51.                 objContext.SaveChanges();  
  52.                 return RedirectToAction("Index");  
  53.             }               
  54.             return View(model);  
  55.         }   
  56.        #endregion   
  57.         #region Delete Publisher  
  58.         public ActionResult Delete(int id)  
  59.         {  
  60.             Publisher publisher = objContext.Publishers.Find(id);//.Where(x => x.PublisherId == id).SingleOrDefault();  
  61.             return View(publisher);  
  62.         }   
  63.         [HttpPost]  
  64.         public ActionResult Delete(int id, Publisher model)  
  65.         {  
  66.            var publisher = objContext.Publishers.Where(x => x.PublisherId == id).SingleOrDefault();  
  67.            if (publisher != null)  
  68.             {  
  69.                 objContext.Publishers.Remove(publisher);  
  70.                 objContext.SaveChanges();  
  71.             }  
  72.             return RedirectToAction("Index");  
  73.         }  
  74.         #endregion   
  75.     }  
  76. }  
The Book controller in the file BookController.cs in the Controllers folder:
  1. using System.Linq;  
  2. using System.Web.Mvc;  
  3. using ExampleCodeFirstApproch.Models;   
  4. namespace ExampleCodeFirstApproch.Controllers  
  5. {  
  6.     public class BookController : Controller  
  7.     {  
  8.        LibraryContext objContext;  
  9.        public BookController()  
  10.         {  
  11.             objContext = new LibraryContext();  
  12.         }   
  13.         #region List and Details Book   
  14.         public ActionResult Index()  
  15.         {  
  16.             var books = objContext.Books.ToList();  
  17.             return View(books);  
  18.         }   
  19.         public ViewResult Details(int id)  
  20.         {  
  21.             Book book = objContext.Books.Where(x=>x.BookId==id).SingleOrDefault();  
  22.             return View(book);  
  23.         }   
  24.         #endregion   
  25.         #region Create Publisher   
  26.         public ActionResult Create()  
  27.         {  
  28.             return View(new Book());  
  29.         }   
  30.         [HttpPost]  
  31.         public ActionResult Create(Book book)  
  32.         {  
  33.             objContext.Books.Add(book);  
  34.             objContext.SaveChanges();  
  35.             return RedirectToAction("Index");  
  36.         }   
  37.         #endregion   
  38.         #region Edit Book   
  39.         public ActionResult Edit(int id)  
  40.         {  
  41.             Book book = objContext.Books.Where(x => x.BookId == id).SingleOrDefault();  
  42.             return View(book);  
  43.         }    
  44.         [HttpPost]  
  45.         public ActionResult Edit(Book model)  
  46.         {  
  47.             Book book = objContext.Books.Where(x => x.BookId == model.BookId).SingleOrDefault();  
  48.             if (book != null)  
  49.             {  
  50.                 objContext.Entry(book).CurrentValues.SetValues(model);  
  51.                 objContext.SaveChanges();  
  52.                 return RedirectToAction("Index");  
  53.             }               
  54.             return View(model);  
  55.         }   
  56.        #endregion   
  57.         #region Delete Book   
  58.         public ActionResult Delete(int id)  
  59.         {  
  60.             Book book = objContext.Books.Find(id);  
  61.             return View(book);  
  62.         }   
  63.         [HttpPost]  
  64.         public ActionResult Delete(int id, Publisher model)  
  65.         {  
  66.            var book = objContext.Books.Where(x => x.BookId == id).SingleOrDefault();  
  67.            if (book != null)  
  68.             {  
  69.                 objContext.Books.Remove(book);  
  70.                 objContext.SaveChanges();  
  71.             }  
  72.             return RedirectToAction("Index");  
  73.         }  
  74.         #endregion  
  75.     }  
  76. }
Both Publisher and Book controllers are ready and create a view according to the action method using a scaffold template and you can download a zip folder. Run the application and you get that your tables are created in the database with a relationship.

image2.gif
Figure 1.2 Relationship between Publishers and Books Tables

Note : Download the source code then change the connection string in the web.config file and run the application. 


Similar Articles