Click here to Skip to main content
15,867,964 members
Articles / Web Development / ASP.NET

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 216.1K   7.2K   98   80
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)

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

    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.

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:

C#
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:

C#
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.
  • 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

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)


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

 
GeneralRe: My vote of 5 Pin
Monjurul Habib15-Nov-12 21:19
professionalMonjurul Habib15-Nov-12 21:19 
GeneralMy vote of 5 Pin
Joe Jalbert27-Sep-12 10:16
Joe Jalbert27-Sep-12 10:16 
GeneralRe: My vote of 5 Pin
Monjurul Habib27-Sep-12 21:17
professionalMonjurul Habib27-Sep-12 21:17 
QuestionNice work Pin
Fahad Mahmood20-Jul-12 20:39
Fahad Mahmood20-Jul-12 20:39 
AnswerRe: Nice work Pin
Monjurul Habib23-Jul-12 14:30
professionalMonjurul Habib23-Jul-12 14:30 
GeneralMy vote of 5 Pin
Unque11-Jul-12 3:16
Unque11-Jul-12 3:16 
GeneralRe: My vote of 5 Pin
Monjurul Habib11-Jul-12 21:44
professionalMonjurul Habib11-Jul-12 21:44 
GeneralMy vote of 5 Pin
pablopecora10-Jul-12 17:05
pablopecora10-Jul-12 17:05 
Excelent article. Very useful.
GeneralRe: My vote of 5 Pin
Monjurul Habib11-Jul-12 21:43
professionalMonjurul Habib11-Jul-12 21:43 
QuestionNeed Help Pin
Ranawaka21-Jun-12 20:23
Ranawaka21-Jun-12 20:23 
AnswerRe: Need Help Pin
Monjurul Habib11-Jul-12 21:45
professionalMonjurul Habib11-Jul-12 21:45 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey8-Jun-12 9:54
professionalManoj Kumar Choubey8-Jun-12 9:54 
GeneralRe: My vote of 5 Pin
Monjurul Habib21-Jun-12 21:17
professionalMonjurul Habib21-Jun-12 21:17 
GeneralMy vote of 5 Pin
Steve Maier20-Mar-12 6:08
professionalSteve Maier20-Mar-12 6:08 
GeneralRe: My vote of 5 Pin
Monjurul Habib20-Mar-12 21:32
professionalMonjurul Habib20-Mar-12 21:32 
GeneralMy vote of 5 Pin
Aftab Quraishi20-Feb-12 21:42
Aftab Quraishi20-Feb-12 21:42 
GeneralRe: My vote of 5 Pin
Monjurul Habib26-Feb-12 0:04
professionalMonjurul Habib26-Feb-12 0:04 
QuestionWait a minute... Pin
Mein Nam31-Jan-12 17:56
Mein Nam31-Jan-12 17:56 
AnswerRe: Wait a minute... Pin
Monjurul Habib4-Feb-12 8:52
professionalMonjurul Habib4-Feb-12 8:52 
GeneralRe: Wait a minute... Pin
Mein Nam4-Feb-12 11:21
Mein Nam4-Feb-12 11:21 
GeneralMy vote of 5 Pin
thatraja22-Jan-12 16:16
professionalthatraja22-Jan-12 16:16 
GeneralRe: My vote of 5 Pin
Monjurul Habib4-Feb-12 8:53
professionalMonjurul Habib4-Feb-12 8:53 
QuestionGenerates error Pin
Dadalus19-Jan-12 12:34
Dadalus19-Jan-12 12:34 
SuggestionMissing parts Pin
Foyzul Karim12-Jan-12 18:52
professionalFoyzul Karim12-Jan-12 18:52 
GeneralRe: Missing parts Pin
Monjurul Habib4-Feb-12 9:01
professionalMonjurul Habib4-Feb-12 9:01 

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.