Click here to Skip to main content
Click here to Skip to main content

How to use Entity Framework Code First for MVC 3

, 20 Sep 2011
Rate this:
Please Sign up or sign in to vote.
Explains in detail how to use Entity Framework Code First for MVC 3.

Introduction

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.)

Introduction

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):

Model

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

View

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

Controller

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

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'.

    step1.JPG

  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.

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.

step5.JPG

step6.JPG

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]

step8.JPG

step9.JPG

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.

step10.JPG

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.
  • Click on Create New and fill the data and save it.
  • You can also Edit, Delete, and also browse the detail for each Author.
  • 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.

Pros & Cons

Pros

  • I hope you already got it (huge).

Cons

  • 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!

License

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

About the Author

Monjurul Habib
Software Developer (Senior)
Bangladesh Bangladesh
A life-long-learner, maker and soft music fan. Likes building things to solve problems. Lives in Dhaka with wife and wonderful, smart kid and works as a Senior Software Engineer in applications architecture team.
 
He has years of successful records serving mid and large scale .NET applications. Have a wide range of experience working in domestic and international client environment. Expertise in different areas of software development life cycles and Software Architecture.
 
I am always looking for new information and value your feedback (especially where I got something wrong!).
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
QuestionNice article PinprofessionalAbhishek Pant9-May-14 3:07 
QuestionMVC3 with EF Pinmemberaniyan.c15-Jan-14 1:56 
AnswerRe: MVC3 with EF PinprofessionalAntariksh Verma12-Mar-14 3:07 
GeneralMy vote of 5 PinmemberslhCoding18-Nov-13 9:34 
GeneralRe: My vote of 5 PinprofessionalMonjurul Habib18-Nov-13 19:55 
GeneralMy vote of 5 Pinmemberrubol31-Jul-13 0:00 
GeneralRe: My vote of 5 PinprofessionalMonjurul Habib1-Aug-13 10:18 
GeneralMy vote of 5 PinprofessionalAntariksh Verma8-Jul-13 1:01 
GeneralRe: My vote of 5 PinprofessionalMonjurul Habib1-Aug-13 10:18 
QuestionExcelente PinmemberDeb1713-Jun-13 18:19 
AnswerRe: Excelente PinprofessionalMonjurul Habib1-Aug-13 10:16 
GeneralMy vote of 5 PinmemberRockstar_30-May-13 21:00 
GeneralRe: My vote of 5 PinprofessionalMonjurul Habib1-Aug-13 10:13 
GeneralMy vote of 4 PinmemberAvik Ghosh2212-Feb-13 6:21 
GeneralRe: My vote of 4 PinmemberAvik Ghosh2212-Feb-13 6:28 
GeneralRe: My vote of 4 PinmemberAvik Ghosh2212-Feb-13 6:30 
QuestionUnable to retrieve metadata for 'MVCFist.Models.Author' One or more validation errors were detected during model generation Pinmemberdestar771-Feb-13 20:00 
AnswerRe: Unable to retrieve metadata for 'MVCFist.Models.Author' One or more validation errors were detected during model generation [modified] PinmemberMonjurul Habib2-Feb-13 7:34 
GeneralRe: Unable to retrieve metadata for 'MVCFist.Models.Author' One or more validation errors were detected during model generation Pinmemberdestar774-Feb-13 16:05 
GeneralMy vote of 4 PinmemberArvind Jiiva23-Jan-13 22:24 
QuestionThanx! Pinmemberraimond12-Jan-13 10:21 
GeneralMy vote of 5 PinmemberBikash Karmokar31-Dec-12 23:39 
QuestionWhere is the database PinmemberMember 342710911-Dec-12 18:48 
AnswerRe: Where is the database PinmemberMonjurul Habib11-Dec-12 21:10 
GeneralMy vote of 1 Pinmembertahir irshad abbasi23-Nov-12 9:56 
GeneralRe: My vote of 1 PinmemberMonjurul Habib23-Nov-12 10:04 
GeneralRe: My vote of 1 Pinmembertahir irshad abbasi23-Nov-12 10:21 
GeneralRe: My vote of 1 PinmemberMonjurul Habib23-Nov-12 19:44 
QuestionGoals Pinmembertahir irshad abbasi23-Nov-12 9:49 
GeneralMy vote of 5 PinmemberMd. YaSiR aRaFaT21-Nov-12 23:48 
GeneralRe: My vote of 5 PinmemberMonjurul Habib22-Nov-12 4:02 
GeneralMy vote of 5 Pinmemberdevbrat15-Nov-12 1:57 
GeneralRe: My vote of 5 PinmemberMonjurul Habib15-Nov-12 21:19 
GeneralMy vote of 5 PinmemberJoe Jalbert27-Sep-12 10:16 
GeneralRe: My vote of 5 PinmemberMonjurul Habib27-Sep-12 21:17 
QuestionNice work PinmemberFahad Mahmood20-Jul-12 20:39 
AnswerRe: Nice work PinmemberMonjurul Habib23-Jul-12 14:30 
GeneralMy vote of 5 PinmemberUnque11-Jul-12 3:16 
GeneralRe: My vote of 5 PinmemberMonjurul Habib11-Jul-12 21:44 
GeneralMy vote of 5 Pinmemberpablopecora10-Jul-12 17:05 
GeneralRe: My vote of 5 PinmemberMonjurul Habib11-Jul-12 21:43 
QuestionNeed Help PinmemberRanawaka21-Jun-12 20:23 
AnswerRe: Need Help PinmemberMonjurul Habib11-Jul-12 21:45 
GeneralMy vote of 5 Pinmembermanoj kumar choubey8-Jun-12 9:54 
GeneralRe: My vote of 5 PinmemberMonjurul Habib21-Jun-12 21:17 
GeneralMy vote of 5 PinmemberSteve Maier20-Mar-12 6:08 
GeneralRe: My vote of 5 PinmemberMonjurul Habib20-Mar-12 21:32 
GeneralMy vote of 5 PinmemberAftab Quraishi20-Feb-12 21:42 
GeneralRe: My vote of 5 PinmemberMonjurul Habib26-Feb-12 0:04 
QuestionWait a minute... PinmemberMein Nam31-Jan-12 17:56 

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 | Mobile
Web03 | 2.8.140721.1 | Last Updated 20 Sep 2011
Article Copyright 2011 by Monjurul Habib
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid