Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to use Entity Framework Code First for MVC 3

0.00/5 (No votes)
20 Sep 2011 1  
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here