Reader Level:
ARTICLE

MVC Application Using EntityFramework Code-First Approach: Part 4

Posted by Akhil Mittal Articles | ASP.NET MVC July 22, 2013
This article focuses on connecting our MVC application with a database using the CodeFirst approach.
  • 4
  • 0
  • 8088

Introduction

In our first three articles, we learned a lot about MVC, from its definition to its use, from creating an application to connecting the MVC application with a database using various techniques.

In the very last part of the series we learned how to connect our MVC application with an existing database using Entity Framework.

This article focuses on connecting our MVC application with a database using the CodeFirst approach, in other words one of the features that Microsoft's Entity Framework provides.

Our Roadmap

Just as a reminder of our full roadmap towards learning MVC, see:

  1. Part 1: Introduction to MVC architecture and Separation of Concerns.
  2. Part 2: Creating MVC Application from scratch and connecting it with database using LINQ to SQL.
  3. Part 3: Connecting the MVC Application using the EntityFramework DB-First approach.
  4. Part 4: Connecting the MVC Application using the EntityFramework Code-First approach.
  5. Part 5: Implementing Repository Pattern in a MVC Application with the EntityFramework.
  6. Part 6: Implementing a generic Repository Pattern and Unit Of Work pattern in a MVC Application with the EntityFramework.

Pre-requisites

The following are pre-requisites for this article:

  1. We have a running sample application that we created in the third part of the article series.
  2. We have the Entity Framework 4.1 package or DLL on our local file system.
  3. We understand how a MVC application is created.

Code-First Approach

To do a domain driven design, the 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 the database automatically from code after defining our domain. The database created perfectly matches with the domain we design, so we need to be very conscious and keen in designing our domain model. It feels exciting to see the database created on the fly using our entities and XML configuration, without even opening a database server.

No matter, you are not an expert in databases, if you are a C# developer then just focus on your model/class creation. The Entity Framework will relieve you of the headache of creating and managing databases.

Procedure

Step 1: Open the MVC application that we created in Learning MVC-Part 3 in your Visual Studio.

MVC1.jpg

We can clearly see and remember what we used to connect our MVC application to the database using Entity Framework, yes it was a edmx class and our Model.tt classes generated from the edmx classes.

Step 2: We don't need an existing database, 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 delete the EFDataModel.edmx, Model1.Context.tt and Model1.tt files. Now please do not run the application, it will give compiler errors , since we were using those classes ;-), Our Solution will look like:

MVC2.jpg

Our old solution had the UserList class in the Models folder, I have only changed the name of the class for differentiating it with the 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:

MVC3.jpg

Step 5: Just add the 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 new class from the DBContext class, as in the following:

MVC4.jpg

DbContext Class: According to the MSDN, the DbContext class is conceptually similar to ObjectContext .To define it, the ObjectContext 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" for tasks that are frequently used but are complicated to code directly with ObjectContext that is a 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, as in the following:

public DbSet<User> Users { get; set; }

User, defined in angular brackets, is the model that we created in the 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<User> Users { get; set; }

    }

}

That's it, 90% of the work is done.

DbSet property: It is a simplified alternative to ObjectSet and performs CRUD operations against a specific type from the model.

By default, the name of the DbContext class will be the name of our database that will be created automatically, so be wise in the selection of the name of the context class, else it could be handled in web.config also.

The name of the model will be the name of the Table in the database and the properties of the model will be the columns of the table.

Our Heroes

MVC4.5.jpg

Both DbContext and DbSet are our super-heroes in creating and dealing with database operations, providing a significant amount of abstraction and ease of use.

When we are working with DbContext, we are actually working with entity sets. DbSet represents a typed entity set that does the creation, reading, update, and deletion of 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 the web.config file, you can remove a previously defined connection string. The new connection string will be somewhat as in the following:

MVC5.jpg

The name of the connection string will be the name of the DbContext that we defined, in other words MVCDbContext.

Step 9: Now we just need to modify the access method in controllers. Earlier, when we created the application in the third part, we were accessing the context class from the modelcontext class that was generated from the edmx file. The edmx file was added with a reference to the previously created database.

But now the case is different, we don't yet have a database, we'll access the table and columns using our MVCDBContext class in controllers, so just change the following line of code used in the Actions of the earlier application:
 

var dbContext = new MVCEntities() ;

to

var dbContext = new MVCDBContext();

Job Done. MVC6.jpg



Just Hit F5 and you'll see:

MVC7.jpg

How does the application run, where is the data base??? Dude, go back to your database server, and check for the database:

MVC8.jpg

We see that our database was created with the name MVCDB. That's the magic of Entity Framework. Now we can do all the CRUD operations on this database, using our application. Just create a new user.

MVC9.jpg

In the database we see the user has been created.

MVC10.jpg

By default, the integer property has ID in its name of the model and will be the primary key in the data base, in our case UserId, or you can define the primary key in the model too.

Conclusion

Now we know how to play with Entity Framework to create a database as per our domain model from our code, we have already moved on to the advanced concepts of MVC and Entity Framework.

MVC11.jpg

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.

Happy Coding :-) . 

COMMENT USING

Trending up