Click here to Skip to main content
11,641,971 members (63,068 online)
Click here to Skip to main content

How to use Entity Framework Code First for MVC 3

, 20 Sep 2011 CPOL 137.5K 6.8K 94
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)

Share

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.

Has 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 information and value feedback (especially where got something wrong!).

You may also be interested in...

Comments and Discussions

 
QuestionNice article Pin
Abhishek Pant9-May-14 3:07
professionalAbhishek Pant9-May-14 3:07 
QuestionMVC3 with EF Pin
aniyan.c15-Jan-14 1:56
memberaniyan.c15-Jan-14 1:56 
AnswerRe: MVC3 with EF Pin
Antariksh Verma12-Mar-14 3:07
professionalAntariksh Verma12-Mar-14 3:07 
GeneralMy vote of 5 Pin
slhCoding18-Nov-13 9:34
memberslhCoding18-Nov-13 9:34 
GeneralRe: My vote of 5 Pin
Monjurul Habib18-Nov-13 19:55
professionalMonjurul Habib18-Nov-13 19:55 
GeneralMy vote of 5 Pin
rubol31-Jul-13 0:00
memberrubol31-Jul-13 0:00 
GeneralRe: My vote of 5 Pin
Monjurul Habib1-Aug-13 10:18
professionalMonjurul Habib1-Aug-13 10:18 
GeneralMy vote of 5 Pin
Antariksh Verma8-Jul-13 1:01
professionalAntariksh Verma8-Jul-13 1:01 
GeneralRe: My vote of 5 Pin
Monjurul Habib1-Aug-13 10:18
professionalMonjurul Habib1-Aug-13 10:18 
QuestionExcelente Pin
Deb1713-Jun-13 18:19
memberDeb1713-Jun-13 18:19 
AnswerRe: Excelente Pin
Monjurul Habib1-Aug-13 10:16
professionalMonjurul Habib1-Aug-13 10:16 
GeneralMy vote of 5 Pin
Rockstar_30-May-13 21:00
memberRockstar_30-May-13 21:00 
GeneralRe: My vote of 5 Pin
Monjurul Habib1-Aug-13 10:13
professionalMonjurul Habib1-Aug-13 10:13 
GeneralMy vote of 4 Pin
Avik Ghosh2212-Feb-13 6:21
memberAvik Ghosh2212-Feb-13 6:21 
GeneralRe: My vote of 4 Pin
Avik Ghosh2212-Feb-13 6:28
memberAvik Ghosh2212-Feb-13 6:28 
GeneralRe: My vote of 4 Pin
Avik Ghosh2212-Feb-13 6:30
memberAvik Ghosh2212-Feb-13 6:30 
QuestionUnable to retrieve metadata for 'MVCFist.Models.Author' One or more validation errors were detected during model generation Pin
destar771-Feb-13 20:00
memberdestar771-Feb-13 20: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 7:34
memberMonjurul Habib2-Feb-13 7:34 
GeneralRe: Unable to retrieve metadata for 'MVCFist.Models.Author' One or more validation errors were detected during model generation Pin
destar774-Feb-13 16:05
memberdestar774-Feb-13 16:05 
GeneralMy vote of 4 Pin
Arvind Jiiva23-Jan-13 22:24
memberArvind Jiiva23-Jan-13 22:24 
QuestionThanx! Pin
raimond12-Jan-13 10:21
memberraimond12-Jan-13 10:21 
GeneralMy vote of 5 Pin
Bikash Karmokar31-Dec-12 23:39
memberBikash Karmokar31-Dec-12 23:39 
QuestionWhere is the database Pin
Member 342710911-Dec-12 18:48
memberMember 342710911-Dec-12 18:48 
AnswerRe: Where is the database Pin
Monjurul Habib11-Dec-12 21:10
memberMonjurul Habib11-Dec-12 21:10 
GeneralMy vote of 1 Pin
tahir irshad abbasi23-Nov-12 9:56
membertahir irshad abbasi23-Nov-12 9:56 
GeneralRe: My vote of 1 Pin
Monjurul Habib23-Nov-12 10:04
memberMonjurul Habib23-Nov-12 10:04 
GeneralRe: My vote of 1 Pin
tahir irshad abbasi23-Nov-12 10:21
membertahir irshad abbasi23-Nov-12 10:21 
GeneralRe: My vote of 1 Pin
Monjurul Habib23-Nov-12 19:44
memberMonjurul Habib23-Nov-12 19:44 
QuestionGoals Pin
tahir irshad abbasi23-Nov-12 9:49
membertahir irshad abbasi23-Nov-12 9:49 
GeneralMy vote of 5 Pin
Md. YaSiR aRaFaT21-Nov-12 23:48
memberMd. YaSiR aRaFaT21-Nov-12 23:48 
GeneralRe: My vote of 5 Pin
Monjurul Habib22-Nov-12 4:02
memberMonjurul Habib22-Nov-12 4:02 
GeneralMy vote of 5 Pin
devbrat15-Nov-12 1:57
memberdevbrat15-Nov-12 1:57 
GeneralRe: My vote of 5 Pin
Monjurul Habib15-Nov-12 21:19
memberMonjurul Habib15-Nov-12 21:19 
GeneralMy vote of 5 Pin
Joe Jalbert27-Sep-12 10:16
memberJoe Jalbert27-Sep-12 10:16 
GeneralRe: My vote of 5 Pin
Monjurul Habib27-Sep-12 21:17
memberMonjurul Habib27-Sep-12 21:17 
QuestionNice work Pin
Fahad Mahmood20-Jul-12 20:39
memberFahad Mahmood20-Jul-12 20:39 
AnswerRe: Nice work Pin
Monjurul Habib23-Jul-12 14:30
memberMonjurul Habib23-Jul-12 14:30 
GeneralMy vote of 5 Pin
Unque11-Jul-12 3:16
memberUnque11-Jul-12 3:16 
GeneralRe: My vote of 5 Pin
Monjurul Habib11-Jul-12 21:44
memberMonjurul Habib11-Jul-12 21:44 
GeneralMy vote of 5 Pin
pablopecora10-Jul-12 17:05
memberpablopecora10-Jul-12 17:05 
GeneralRe: My vote of 5 Pin
Monjurul Habib11-Jul-12 21:43
memberMonjurul Habib11-Jul-12 21:43 
QuestionNeed Help Pin
Ranawaka21-Jun-12 20:23
memberRanawaka21-Jun-12 20:23 
AnswerRe: Need Help Pin
Monjurul Habib11-Jul-12 21:45
memberMonjurul Habib11-Jul-12 21:45 
GeneralMy vote of 5 Pin
manoj kumar choubey8-Jun-12 9:54
membermanoj kumar choubey8-Jun-12 9:54 
GeneralRe: My vote of 5 Pin
Monjurul Habib21-Jun-12 21:17
memberMonjurul Habib21-Jun-12 21:17 
GeneralMy vote of 5 Pin
Steve Maier20-Mar-12 6:08
memberSteve Maier20-Mar-12 6:08 
GeneralRe: My vote of 5 Pin
Monjurul Habib20-Mar-12 21:32
memberMonjurul Habib20-Mar-12 21:32 
GeneralMy vote of 5 Pin
Aftab Quraishi20-Feb-12 21:42
memberAftab Quraishi20-Feb-12 21:42 
GeneralRe: My vote of 5 Pin
Monjurul Habib26-Feb-12 0:04
memberMonjurul Habib26-Feb-12 0:04 
QuestionWait a minute... Pin
Mein Nam31-Jan-12 17:56
memberMein 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 | Terms of Use | Mobile
Web03 | 2.8.150731.1 | Last Updated 20 Sep 2011
Article Copyright 2011 by Monjurul Habib
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid