Click here to Skip to main content
11,637,415 members (67,284 online)
Click here to Skip to main content

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

, 17 Mar 2015 CPOL 77.1K 5.2K 87
Rate this:
Please Sign up or sign in to vote.
MVC Application using 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 delete EFDataModel.edmx, Model1.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 Wink | ;-) , 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 from DBContext class,

DbContext class: According to MSDN, DbContext class is conceptually similar to ObjectContext. To define, 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” 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<User> 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<User> 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 our MVCDBContext 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.

For more informative articles,visit my blog A Practical Approach  

Learn  Code First Approach using Entity Framework 4.1, Inversion of Control, Unity Framework, Repository & Unit of Work Pattern and MVC3 Razor View  , a complete end to end solution.  

Happy coding! Smile | :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Akhil Mittal
Technical Lead
India India
I am a C# Corner MVP,a Code project MVP,blogger,programmer by heart and currently working as a Sr. Analyst in Magic Software and have an experience of more than 8 years in C#.Net. I am a B.Tech in Computer Science and hold a diploma in Information Security and Application Development. My work experience includes Development of Enterprise Applications using C#,.Net and Sql Server,Analysis as well as Research and Development. I am a MCP in Web Applications(MCTS-70-528,MCTS-70-515) and .Net Framework 2.0 (MCTS-70-536). Visit my personal blog A Practical Approach for more informative articles.
____________________________________________________________________________________________________

Article of the Day on Microsoft's site http://www.asp.net/community/articles on 16 Aug 2013.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 28 Aug 2013.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 08 Sept 2013.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 29 Sept 2013.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 29 Oct 2013.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 21 May 2014.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 19 July 2014.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 01 June 2015.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 02 June 2015.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 08 June 2015.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 28 June 2015.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 28 July 2015.
Member of the month for July 2013 on C# Corner
May 2014 Month
Group type: Collaborative Group

267 members


You may also be interested in...

Comments and Discussions

 
GeneralMy Vote 5 Pin
Dharmesh .S. Patil2-Jul-15 0:00
professionalDharmesh .S. Patil2-Jul-15 0:00 
GeneralRe: My Vote 5 Pin
Akhil Mittal 2-Jul-15 0:01
mvp Akhil Mittal 2-Jul-15 0:01 
GeneralRe: My Vote 5 Pin
Dharmesh .S. Patil2-Jul-15 0:19
professionalDharmesh .S. Patil2-Jul-15 0:19 
GeneralRe: My Vote 5 Pin
Akhil Mittal 2-Jul-15 0:20
mvp Akhil Mittal 2-Jul-15 0:20 
QuestionGood Article ! Pin
Jenny B Jones10-Apr-15 3:06
professionalJenny B Jones10-Apr-15 3:06 
AnswerRe: Good Article ! Pin
Akhil Mittal 4-May-15 19:53
mvp Akhil Mittal 4-May-15 19:53 
AnswerRe: Good Article ! Pin
Akhil Mittal 18-May-15 18:53
mvp Akhil Mittal 18-May-15 18:53 
QuestionDatabase is not creating in my application . Pin
Desh Deepak verma8-May-14 21:10
memberDesh Deepak verma8-May-14 21:10 
AnswerRe: Database is not creating in my application . Pin
Akhil_Mittal9-May-14 7:12
mvpAkhil_Mittal9-May-14 7:12 
GeneralMy vote of 5 Pin
Rahul Rajat Singh29-Nov-13 0:07
mvpRahul Rajat Singh29-Nov-13 0:07 
GeneralRe: My vote of 5 Pin
Akhil_Mittal29-Nov-13 0:17
groupAkhil_Mittal29-Nov-13 0:17 
GeneralMy vote of 5 Pin
Antariksh Verma17-Sep-13 22:51
professionalAntariksh Verma17-Sep-13 22:51 
QuestionWell Detailed Pin
gssiva1-Sep-13 3:18
membergssiva1-Sep-13 3:18 
AnswerRe: Well Detailed Pin
Akhil_Mittal3-Sep-13 2:23
groupAkhil_Mittal3-Sep-13 2:23 
GeneralMy vote of 5 Pin
JrPacheco30-Aug-13 9:37
memberJrPacheco30-Aug-13 9:37 
GeneralRe: My vote of 5 Pin
Akhil_Mittal30-Aug-13 22:32
groupAkhil_Mittal30-Aug-13 22:32 
GeneralMy vote of 5 Pin
frankfajardo23-Aug-13 3:26
memberfrankfajardo23-Aug-13 3:26 
GeneralRe: My vote of 5 Pin
Akhil_Mittal27-Aug-13 23:58
groupAkhil_Mittal27-Aug-13 23:58 
GeneralMy vote of 5 Pin
garg prachi15-Aug-13 4:18
membergarg prachi15-Aug-13 4:18 
GeneralMy vote of 5 Pin
gupta_pankaj_magic14-Aug-13 6:38
membergupta_pankaj_magic14-Aug-13 6:38 
GeneralMy vote of 4 Pin
kvicky12-Aug-13 18:59
memberkvicky12-Aug-13 18:59 
GeneralMy vote of 5 Pin
Member 1020215510-Aug-13 22:32
memberMember 1020215510-Aug-13 22:32 
GeneralMy vote of 5 Pin
Member 101973838-Aug-13 1:08
memberMember 101973838-Aug-13 1:08 
GeneralMy vote of 5 Pin
Adarsh chauhan5-Aug-13 2:51
memberAdarsh chauhan5-Aug-13 2:51 
GeneralRe: My vote of 5 Pin
Akhil_Mittal5-Aug-13 3:00
groupAkhil_Mittal5-Aug-13 3:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150728.1 | Last Updated 18 Mar 2015
Article Copyright 2013 by Akhil Mittal
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid