Click here to Skip to main content
15,569,234 members
Articles / Web Development / ASP.NET
Posted 20 Sep 2011


98 bookmarked

How to use Entity Framework Code First for MVC 3

Rate me:
Please Sign up or sign in to vote.
4.90/5 (60 votes)
20 Sep 2011CPOL6 min read
Explains in detail how to use Entity Framework Code First for MVC 3.


You might be surprised why I am writing an MVC EF Code First article when lots are already available on the web! But it is very tough for a beginner to consolidate all of them. Also I will try to post a series of step by step articles. Let's now start with an introduction.

Recommended Prerequisites

  • Visual Studio 2010 SP1
  • SQL Express
  • ASP.NET MVC 3 (If you have already properly installed Visual Studio 2010 SP1, it is already there, else you will find it over here.)


Microsoft’s ADO.NET Entity Framework (EF) simplifies data access to avoid working directly with the database in your code. Entity Framework handles all the database interactions. There is no need to write extra code for any kind of joins between entities as it works with your objects in memory.

Visual Studio 2010 provides richer EF design and tool support. The EF designer in VS 2010 supports both a “database first” development style – where you construct your model layer on a design surface from an existing database, and a “model first” development style – where you first define your model layer using the design surface and then use it to generate a database schema from it.

Code First

EF4 also enables a more code-centric option which we call “Code First development”. When using Code First development, you will begin by writing .NET classes that define your conceptual (domain) model. Then you can use your model to generate a database schema or can map to an existing database.

As the first thing you do is write code to describe your entities, and you can simply define the classes and let EF work with those, it is called “Code First development”. Code First has the following advantages:

  • Develop without ever having to open a designer or define an XML mapping file
  • Define your model objects by simply writing “plain old classes” with no base classes required
  • Use a “convention over configuration” approach that enables database persistence without explicitly configuring anything
  • Optionally override the convention-based persistence and use a Fluent code API to fully customize persistence mapping

Tiny Fundamentals on MVC (Model View Controller):


  • business logic
  • can use any of the following:
    • LINQ to SQL
    • Entity Framework
    • nHibernate
    • and more..


  • No business logic, only display logic
  • JavaScript-jQuery for client-side validation


  • Contains Action
  • Works a request gateway
  • Decision maker (decide which data is needed, which Model to render, and which View to render)

Image 1

If you look at the above image, you will find Models, Views, and Controllers folders. I will discuss them in detail later. Here I am giving you just an introduction.

Let's Create an MVC 3 Application

  1. On your Visual Studio 2010, go to File->New->Project.
  2. On Visual C#->Web Section, you will see an option to create an 'ASP.NET MVC 3' application, select that, set your other preferences (project name, project directory), and click OK.
  3. Remember, don't go with the option 'File->New->Website'.


  4. On the next ASP.NET MVC 3 Project wizard, select "Internet Application", and "Razor" as the View Engine.
  5. step2.JPG

Visual Studio creates a full project structure automatically for you including those folders that contain pre-built controller classes, models, views, and "Scripts", "Content" for jQuery, JavaScript, and CSS files.

Image 4

If you Run your project now, you will find its default content which is simply a message welcoming you to MVC and a basic layout with home/about/login/register pages.

You can change the welcome message. If you open "Views/Home/Index.cshtml" (Razor View), you will get @ViewBag.Message. As @ViewBag refers to a dynamic type collection, it is possible to assign any type of element inside. If you open "Controllers/HomeController.cs", you will find:

public ActionResult Index()
    ViewBag.Message = "Welcome to ASP.NET MVC!";
    return View();

Assign Hello World! instead of Welcome to ASP.NET MVC! to ViewBag.Message.

There are some things you should know at this point:

  • Extension of a Razor based View is .cshtml for a View that uses C# and .vbhtml for a View that uses VB.NET.
  • Files that cannot be shown by direct requests (master pages, partial views, etc.) have underscore (_) in the beginning of their names.

Now Build and run your application. This is your first Hello World in MVC 3.

Entity Framework Code First

You do not need to begin your application by creating a database or specifying schema. You can start by writing classes that define the domain model objects, which is most appropriate for our application – without the hassle of intermixing data persistence logic.

Create a model class, for example "Author", it will create an empty class.



Write the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace OpenLibrary.Models
    public class Author
        public int AuthorId { get; set; }
        [Required] //Anotation
        public string Name { get; set; }
        public string Address1 { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public DateTime DOB { get; set; }

        public virtual ICollection<book> Books { get; set; }
        // Author have collect of Books
    public class Book 
        public int BookId { get; set; }
        public string Name { get; set; }
        public DateTime PublishDate { get; set; }
        // Ref. for the Author . It helps to relate the two class
        // and also helps to create the EF Code First data Base
        public int AuthorId { get; set; } 

        public virtual Author Author{get;set;} //virtual property to access Author


It's just code. Not derived from the database. Notice that I've put the [Required] annotation on this class. The Required annotation tells EF that a particular property is required. Adding Required to the Name property will force EF and MVC to ensure that the property has data in it. I will discuss Code First DataAnnotations later.

Next, make an Author Controller, via right|click Add Controller:

  • Define a controller name
  • Template [Controller with read/write actions and views, using Entity Framework]
  • Model class [Author(OpenLibrary.Models)]
  • Data context class [Click on the new data context, another modal window will appear, click OK and then Add]
  • Next, make a Book Controller, via right|click Add Controller:

  • Define a controller name
  • Template [Controller with read/write actions and views, using Entity Framework]
  • Model class [Book(OpenLibrary.Models)]
  • Data context class [Use the same data context and click Add]



Look at Solution Explorer and you will find auto generated code. The context class holds the Authors and Books for EF. You can access the class from your Controller and all the generated classes. You can also access all the auto generated Create, Delete, Details, Edit, and Index views in Razor. If you open the Controllers, you will find those methods as well. So you have got auto generated Views and Controls from the Model you created.


Next open Models/OpenLibraryContext.cs, and you will find DBContext and DBSet there.

When you run the application, DBContext checks if there is any model for the type of derived context and any connection string that is already cached in the application domain. If it is already there, then it uses that model, or the DBContext works out what classes to include in the model based on what DbSet properties were defined. Then it uses the default Code First conventions and additional configuration that you specified through annotations or Fluent API to build the model. The System.Data.Entity.DbSet properties are automatically initialized when the instance of the derived DbContext class is created.

Now run the project and enjoy CRUD:

  • Write Author in the URL area and you will find an empty Author listing page.
  • Image 10

  • Click on Create New and fill the data and save it.
  • You can also Edit, Delete, and also browse the detail for each Author.
  • Image 11

  • Write Book in the URL area and click on Create New.
  • You will find an Author dropdown on the Book/Create page. Select and save the book detail.
  • Image 12

Pros & Cons


  • I hope you already got it (huge).


  • Mapping entities to the database is quite complex.
  • There is no Model diagram.

As it is an introduction, this is a really basic example, but I like it. It takes just a few minutes to get a lot done without much code and effort. Hope you enjoyed this. Have fun!


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

Written By
Software Developer (Senior)
Singapore Singapore
A life-long-learner, maker and soft music fan. Likes building things to solve problems. Years of successful records serving mid and large scale .NET applications in domestic and international client environment. Expertise in different areas of software development life cycles and Software Architecture.

Always looks for new technology and loves to get hands dirty Smile | :)

Comments and Discussions

QuestionNice article Pin
Abhishek Pant9-May-14 4:07
professionalAbhishek Pant9-May-14 4:07 
QuestionMVC3 with EF Pin
aniyan.c15-Jan-14 2:56
aniyan.c15-Jan-14 2:56 
AnswerRe: MVC3 with EF Pin
Antariksh Verma12-Mar-14 4:07
professionalAntariksh Verma12-Mar-14 4:07 
GeneralMy vote of 5 Pin
slhCoding18-Nov-13 10:34
slhCoding18-Nov-13 10:34 
GeneralRe: My vote of 5 Pin
Monjurul Habib18-Nov-13 20:55
professionalMonjurul Habib18-Nov-13 20:55 
GeneralMy vote of 5 Pin
Rubol31-Jul-13 1:00
professionalRubol31-Jul-13 1:00 
GeneralRe: My vote of 5 Pin
Monjurul Habib1-Aug-13 11:18
professionalMonjurul Habib1-Aug-13 11:18 
GeneralMy vote of 5 Pin
Antariksh Verma8-Jul-13 2:01
professionalAntariksh Verma8-Jul-13 2:01 
GeneralRe: My vote of 5 Pin
Monjurul Habib1-Aug-13 11:18
professionalMonjurul Habib1-Aug-13 11:18 
QuestionExcelente Pin
Deb1713-Jun-13 19:19
Deb1713-Jun-13 19:19 
AnswerRe: Excelente Pin
Monjurul Habib1-Aug-13 11:16
professionalMonjurul Habib1-Aug-13 11:16 
GeneralMy vote of 5 Pin
Rockstar_30-May-13 22:00
professionalRockstar_30-May-13 22:00 
GeneralRe: My vote of 5 Pin
Monjurul Habib1-Aug-13 11:13
professionalMonjurul Habib1-Aug-13 11:13 
GeneralMy vote of 4 Pin
Avik Ghosh2212-Feb-13 7:21
Avik Ghosh2212-Feb-13 7:21 
GeneralRe: My vote of 4 Pin
Avik Ghosh2212-Feb-13 7:28
Avik Ghosh2212-Feb-13 7:28 
GeneralRe: My vote of 4 Pin
Avik Ghosh2212-Feb-13 7:30
Avik Ghosh2212-Feb-13 7:30 
QuestionUnable to retrieve metadata for 'MVCFist.Models.Author' One or more validation errors were detected during model generation Pin
destar771-Feb-13 21:00
destar771-Feb-13 21:00 
AnswerRe: Unable to retrieve metadata for 'MVCFist.Models.Author' One or more validation errors were detected during model generation Pin
Monjurul Habib2-Feb-13 8:34
professionalMonjurul Habib2-Feb-13 8:34 
GeneralRe: Unable to retrieve metadata for 'MVCFist.Models.Author' One or more validation errors were detected during model generation Pin
destar774-Feb-13 17:05
destar774-Feb-13 17:05 
GeneralMy vote of 4 Pin
Arvind Jiiva23-Jan-13 23:24
Arvind Jiiva23-Jan-13 23:24 
QuestionThanx! Pin
raimond12-Jan-13 11:21
raimond12-Jan-13 11:21 
GeneralMy vote of 5 Pin
Bikash Karmokar1-Jan-13 0:39
Bikash Karmokar1-Jan-13 0:39 
QuestionWhere is the database Pin
Member 342710911-Dec-12 19:48
Member 342710911-Dec-12 19:48 
AnswerRe: Where is the database Pin
Monjurul Habib11-Dec-12 22:10
professionalMonjurul Habib11-Dec-12 22:10 
GeneralMy vote of 1 Pin
tahir irshad abbasi23-Nov-12 10:56
tahir irshad abbasi23-Nov-12 10:56 

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

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