Skip to main content

Building an MVC 3 App with Model First and Entity Framework 4.1

Julie Lerman

March 2011

Watch a video of this content

Watch a video of this content

Download the code for this article:


Microsoft’s ADO.NET Entity Framework (EF) simplifies data access by allowing you to avoid working directly with the database in your code. Instead you can retrieve data by writing queries against strongly typed classes letting the Entity Framework handle the database interaction on your behalf. EF can also persist changes back to the database for you. In addition to this benefit, you will also benefit from the EF’s comprehension of relationships. This means you will not be required to write extra code to specify joins between entities when expressing queries or simply working with your objects in memory.

EF provides you with three ways to define the model of your entities. Using the database first workflow, you can begin with a legacy database to create a mode. With the model first workflow, you  can design a model in a designer. Or you can simply define classes and let EF work with those—referred to as code first.

In this whitepaper, I will walk you through creating a simple MVC 3 application using Entity Framework’s model first workflow and then use features introduced in Entity Framework 4.1 DbContext API to write your data access code.

Overview

In this walkthrough you will build pieces of a blogging application. The walkthrough will not result in a fully functional blogging application, but instead it will use the blog objects to demonstrate Model  First’s features. You will:

  • Define an Entity Data Model to represent the entities for a blog — Blog, Post and Comment.
  • Generate classes from the model using the ADO.NET DbContext Generator template.
  • Let the model designer help you create a database for your data.
  • Build a simple ASP.NET MVC 3 application that will let you view, add, edit and delete blogs.

Creating the MVC Application

For this demo, all of the code will live inside of an MVC 3 project, so the first step will be to create that project. You’ll use a template that will set up much of the structure for the application.

If you have not installed MVC 3 you can find the download and instructions at Microsoft’s official site for ASP.NET MVC: http://www.asp.net/mvc/mvc3.

  1. In Visual Studio 2010, add a new project by selecting the File menu, then New and then Project.
  2. In the Search Installed Templates text box (top right), type MVC 3 to filter down the list of project templates.
  3. Select ASP.NET MVC 3 Web Application using your language of choice. This walkthrough will use C# code, but you can find both C# and Visual Basic versions in the sample solutions download.
  4. Name the project ModelFirstMVC and then click OK.
  5. In the New ASP.NET MVC 3 Project wizard, choose Internet Application.
  6. Leave the default values of the other options and click OK.


Figure 1: Creating a new MVC 3 Project

Visual Studio will create a full project structure for you including folders that contain pre-built controller classes, models and views. In fact you can run the application already to see it’s default content which is simply a message welcoming you to MVC.

Creating the Model for the Blogging Application

The “M” in MVC stands for model. It doesn’t necessarily mean an Entity Data Model (EDM), but any set of classes that represent your domain. In this application, the Entity Data Model that you will create and more specifically, the Blog, Post and Comment classes that the designer will generate from that EDM, will provide the model for this MVC 3 application. The EDM will go into the Models folder in the project.

With Entity Framework’s Model First workflow, you begin with an empty Entity Data Model and design it in the Entity Data Model Designer.

  1. In Solution Explorer, right click the Models folder.
  2. Select Add and then New Item from the menu.
  3. In the Add New Item dialog, type Entity in the search box in the upper right hand corner.
  4. Select ADO.NET Entity Data Model from the filtered list of item templates.
  5. Change the name of the model to BlogModel.edmx.
  6. In the Choose Model Contents window. Select Empty Model and then click the Finish button.


Figure 2

Visual Studio will open the Entity Data Model designer. Its surface will be empty. Time to create your first entity!

  1. Right click on the designer surface
  2. Select Add, then Entity from the menu.
  3. In the Add Entity Dialog, change the Entity name to Blog, then click OK.

A new Blog entity will be created with a single property, Id, and shown on the designer surface.

 


Figure 3

The wizard gave you the Id property, now you must manually add more properties to this entity. The Blog entity won’t have many properties. Here is the end goal.

 


Figure 4

There are a number of ways to add properties. We’ll go the keyboard route.

  1. Click either the word Properties or the Id property in the entity.
  2. Press the Insert key on your keyboard. This will add a new property with the default name: Property, and default type: String.
  3. Type over the name to change it to Title.
  4. Add another new property using the Insert key and give it the name, BloggerName.

Since both of these properties are strings, you won’t have to change the type of either property. Another default for new properties is that they are non-nullable. You can see in the Properties window for either of those properties that the Nullable property is False, but there’s no need to change that for this walkthrough.

The next entity to create is Post.

 


Figure 5

The DateCreated property will default as a String so you’ll need to change its type as well as allow Content to be nullable.

  1. Repeat the steps above to create the new Post entity and its three additional properties.
  2. Select the DateCreated property in the Post entity.
  3. If you don’t see the Properties window for DateCreated, right click on DateCreated and select Properties from its menu.
  4. In the Properties window, select the Type property.
  5. Using the dropdown list, change the value from String to DateTime.
  6. Select the Content property in the Post entity.
  7. In the Properties window for Content, change the value of Nullable to True.

The entities look great but there’s one more important step: creating a relationship between the two. In an Entity Data Model, a relationship is called an Association.

  1. Right click the Blog entity.
  2. From its context menu choose Add and then Association.

The Add Association screen will be pre-populated. The EDM Designer makes its best guess for the Association settings. In this case because there was only one other entity in the model and it guessed exactly right. This association will create a one-to-many relationship between Blog and Post. The wizard will also create special properties, called Navigation Properties, in each of the entities and finally it will add a foreign key into the child (Post) to refer back to the Id of its parent (Blog). For this walkthrough, all of the default choices in the wizard are just right.

 


Figure 6

  1. Click OK.

The designer will then act on all of the settings in the wizard. As you can see in Figure 7, there is an association line between the entities with indications that Blog is the one (1) in the one-to-many relationship and that Post is the many (*). Blog has a new Navigation property, Posts, that will let you easily navigate to its related Posts,  and Post has a property that will let you navigate back to its’ Blog. Finally notice that the Post has a new foreign key property, BlogId.

 


Figure 7

If you’d like to practice some more, add an entity to represent comments and then create a one-to-many relationship between Post and the new Comment entity as shown in Figure 8.

 


Figure 8

Generating Strongly Typed Entity Classes

As you write your application, you’ll be working with strongly typed classes that are based on your entities. The Entity Data Model designer uses a code generator in Visual Studio called the Text Template Transformation Toolkit (T4). Entity Framework will automatically generate a Blog class, a Post class and if you added the Comment entity, a Comment class.  When you created the new empty model and named it BlogModel, the designer created a default container named BlogModelContainer to represent the container that encapsulates your entities. The code generator will create a class based on this also called BlogModelContainer.

By default, the designer uses a template that results in entity classes that inherit from Entity Framework’s EntityObject and a container class which inherits from EF’s ObjectContext.

These base classes can be cumbersome to work with for a number of reasons. While the ObjectContext is extremely useful when you need a lot of control over Entity Framework’s behavior, the lighter weight DbContext provides access to the most commonly needed tasks and simplifies your coding. The EntityObject derived classes won’t get in your way if you are building simple applications, but in a larger application, you might find that EntityObjects limit which coding patterns you can implement.

Microsoft provides a number of alternative T4 templates for generating classes from the EDM.  When you installed the EF 4.1, a template for creating simpler classes including the DbContext was added to Visual Studio. Let’s tell the designer to use this template instead of the default.

  1. Right click on the model’s designer surface.
  2. From the context menu, choose Add Code Generation Item.
  3. In the Add New Item dialog that opens, select Code from the list of installed templates types on the left.
  4. Choose the ADO.NET DbContext Generator then click the Add button.

Two new files will be listed in Solution Explorer, Model1.Context.tt and Model1.tt. These are template files. Expand the templates to see the generated classes as shown in Figure 9.

 


Figure 9

The Model1.Context file generated from the first template contains the BlogModelContainer class shown here:

public partial class BlogModelContainer : DbContext
    {
        public BlogModelContainer()
            : base("name=BlogModelContainer")
        {
        }
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }
        public DbSet<Comment> Comments { get; set; }
    }

The Model1.tt file generated classes from each of the entities. Here for example, is the blog class which contains 11 lines of code compared to about 130 lines of code generated by the default template.

public partial class Blog
    {
        public Blog()
        {
            this.Posts = new HashSet<Post>();
        }
        public int Id { get; set; }
        public string Title { get; set; }
        public string BloggerName { get; set; }
        public virtual ICollection<Post> Posts { get; set; }
    }

You’ll be using the BlogModelContainer and the generated entity classes to query and update a database in your MVC application — a database which you will create in the next steps.

Creating the Database to Store your Entity Data

Now that you’ve defined your model in the designer, it’s time to leverage Entity Framework’s Model First feature to help you create a database to store your blog data. Using the model information, the EDM Designer can create SQL that when executed will build schema in an existing database to match the schema of your model. Visual Studio will give you a chance to also create the database as well if it doesn’t already exist.

  1. Save your work!
  2. Right click the background of the model’s designer surface.
  3. From the context menu, select Generate Database from Model.
  4. In the Generate Database Wizard, click the New Connection button.
  5. This walkthrough will use a SQL Express database which requires a Microsoft SQL Server (SqlClient) data source. If necessary, change the data source to indicate that. 
  6. Enter .\SQLExpress in the server name.
  7. Enter BlogData in the database name text box as shown in Figure 10.
  8. Click OK.
  9. When prompted to create the new database, click YES. This will bring you back to the Generate Database Wizard.
  10. Ensure that BlogData is now the selected data connection and click Next.
  11. Visual Studio will create the SQL to create the database schema (Database Description Language or DDL) and present it in a window. Click Finish.

 


Figure 10

In response, a new sql file is added to the project inside the Models folder and the BlogData database is created. The designer also added a connection string into the applications web.config file and created some other behind the scenes metadata that will help EF interact with the database.

It is your job to execute the sql to create the tables and other schema of the BlogData database. You’ll need to open the sql file in Visual Studio’s Transact-SQL Editor and connect it to the BlogData database.

  1. Double click the BlogModel.edmx.sql file from Solution Explorer if it’s not already open.
  2. Right click the editor window and select Execute SQL.
  3. In the Connect to Database Engine window, ensure that the Server Name is .\SQLExpress.
  4. Click Connect at the bottom of the dialog box.

When complete, you should see the message, Command(s) completed successfully.

If you want to verify the database that Visual Studio created, open the Server Explorer and expand the sqlexpress.BlogData.dbo. Figure 11 shows the database schema in the Server Explorer.

 


Figure 11

Now you’ve got your model, your classes and your database in place.

Let’s see how they all work in an application. It’s time to return to the MVC 3 application that will let you view, create, edit and delete blogs. At the end of this article, you’ll find a link to another article that will show you how to add Posts to this application.

Creating the Controller Logic for the Blog Class

The “C” in MVC stands for controller. A controller gathers up data and sends it to a view. In MVC, you can create a controller to act as a repository for a specific class and then have it act as a bridge between your classes and the various views. Our controllers will use the BlogModelContainer to retrieve data for us. In a more advanced application, you should separate logic further and would not be working with the BlogModelContainer directly from the controller.

For the Blog class, we’ll be creating one view that displays a list of available Blogs and another that lets users create new Blogs. Therefore the controller will need one method to gather up a list of blogs to present in the first view, another method to provide a view to enter information for a new blog and finally a method to handle saving that new blog back to a database.

The project template created a controller called Home with a set of views and another controller called Account with its own set of views. We’ll ignore those and create our own controllers and views, starting with a controller for the Blog class.

  1. Build the project by choosing Build from the Visual Studio menu and then Build ModelFirstMVC from its drop-down menu.
  2. In the Solution Explorer, right click the Controllers folder.
  3. Click Add from its context menu and then Controller.
  4. In the Add Controller window, change the Controller Name to BlogController and check the Add action methods checkbox.
  5. Click the Add button.

The BlogController class will be created with ActionResult methods: Index, Details, Create, Edit and Delete.

The job of the Index method will be to return a list of Blogs to be displayed in a view. The default code returns an empty View. Change the Index method code to the following:

public ActionResult Index()
        {
          using (var db = new BlogModelContainer ())
          {
            return View(db.Blogs.ToList());
          }
        }

The revised method instantiates a new BlogModelContainer and uses that to query for Blogs then return the results in a List. Entity Framework will take care of converting this into a SQL query, executing the query in the database, capturing the database results and transforming them into Blog objects. That single line of code, db.Blogs.ToList(), is responsible for all of those tasks..

Creating the Index View to Display the Blog List

We’ll add an Index view so that you can see what happens to the results of the Index method.

  1. Right click anywhere in the Index method declaration (public ActionResult Index()).
  2. In the context menu that opens click the Add View option.

 


Figure 12: Adding a view to a controller ActionResult

  1. The AddView dialog will open with the View name already set to Index.
  2. Check the Create a strongly typed view checkbox.
  3. Drop down the Model class option and select Blog.
  4. From the Scaffold template options select List.

These selections will force Visual Studio to create a new web page with markup to display a list of Blogs. The markup for this web page will use the new MVC Razor syntax. Figure 13 shows the Add View dialog.

  1. Click Add to complete the view creation.

 


Figure 13: Creating a new view to display a list of Blog types

Visual Studio will create a Blog folder inside of the Views folder and add the new Index view to that folder as shown in Figure 14.

 


Figure 14: The new Blog Index View is added to the Views/Blog folder

Since the very first call to this method will create a new database, the list of blogs will be empty and you’ll have to begin by creating new blogs.  This is where the two Create methods come into play. Let’s add in the Create logic and View before running the app. Note that you’ll need to make a change to the global.asax file before running the app anyway. You’ll do this shortly.

Adding Controller Logic to Create New Blogs

The first Create method does not need to return anything along with the View. Its View will be used to enter details for a new blog, so those details will start out empty. You don’t need to make any changes to this method.

public ActionResult Create()
        {
            return View();
        }

The second Create method is of more interest. This is the one that will be called when the Create view posts back. By default, the template told this Create method to expect a FormCollection to be passed in as a parameter.

[HttpPost]
        public ActionResult Create(FormCollection collection)

Because the Create view was created as a strongly-typed view, it will be able to pass back a strongly typed Blog object. This means you can change that signature so that the method receives a Blog type.  That will simplify the task of adding the new blog to the BlogModelContainer and saving it back to the database using Entity Framework code.

Modify the Create method overload (the second Create method) to match the following code:

[HttpPost]
    public ActionResult Create(Blog blog)
    {
      try
      {
        using (var db = new BlogModelContainer())
        {
          db.Blogs.Add(blog);
          db.SaveChanges();
        }
        return RedirectToAction("Index");
      }
      catch
      {
        return View();
      }
    }

In this method, you are taking the new blog that is passed in and adding it to the BlogModelContainer’s collection of Blogs, then calling Entity Framework’s SaveChanges method. When .NET executes SaveChanges, it will construct and then execute a SQL INSERT command using the values of the Blog property to create a new row in the Blogs table of the database. If that is successful, then MVC will call the Index method which will return the user to the Index view, listing all of the existing blogs including the newly created blog.

Adding a View for the Create Action

Next, create a view for the Create ActionResult as you did for Index. You can right click either of the Create methods but you only need to build one Create view. Be sure to choose the Create Scaffold template this time.

 


Figure 15: Creating a new view to allow users to add a new Blog.

The new view will be added to the Views/Blog folder along with the Index view you created.

Running the Application

When you first created the MVC application with the template defaults, Visual Studio created a global.asax file that has in it an instruction, called a routing, that tells the application to start with the Index view of the Home controller. You’ll need to change that to start with the Index View of the Blog controller instead.

  • Open the global.asax file from Solution Explorer.
  • Modify the MapRoute call to change the value of controller from “Home” to “Blog”.
routes.MapRoute(
  "Default", // Route name
  "{controller}/{action}/{id}", // URL with parameters
  new { controller = "Blog", action = "Index", id = UrlParameter.Optional }

Now when you run the application the BlogController.Index action will be the first method called. In turn it will execute the code, retrieving a list of Blogs and returning it into the default view (the view of the same name, Index). This is what you will see. Note that I’ve made minor changes to the page’s header in the Shared/ _Layout.cshtml file and the heading of the Index View.

 


Figure 16

Not much to see here except that when you return a View from the BlogController Index method, MVC will find the Blog Index view and display that along with whatever was passed in, which in this case was an empty list.

Clicking the Create New link will call the Create method which returns the Create view.  After entering some information, such as that shown in Figure 17 and clicking the Create button, control is passed back to the Controller, this time calling the Create post back method.

 


Figure 17

The view pushed a blog instance back to the Create method, which then uses the BlogContext to push that data into the database. The Create method then redirects to the Index method which re-queries the database and returns the Index View along with the list of Blogs. This time the list has a single item in it and is displayed as shown in Figure 18.

 


Figure 18

Implementing Edit and Delete

Thus far you have queried for data and added new data. Now you’ll see how Entity Framework lets you edit and delete data just as easily.

To demonstrate this you’ll use the BlogController’s Edit and Delete methods. This means you’ll need the corresponding Views.

  1. Create an Edit View from the BlogController Edit method. Be sure to select a strongly typed view for the Blog class and the Edit scaffolding type.
  2. Create a Delete View from the Blog Controller Edit method. Again, you must select a strongly typed view for the Blog class and this time, the Delete scaffolding type.

When a user edits a blog you will first need to retrieve that particular blog and then send it back to the Edit view.  You can take advantage of Entity Framework 4.1’s Find method which by default searches the entity’s key property using the value passed in. In this case, we’ll find the Blog with an Id field that matches the value of id.

  1. Modify the Edit method to match the following code:
public ActionResult Edit(int id)
        {
          using (var db = new BlogModelContainer())
          {
               return View(db.Blogs.Find(id));
          }
        }

The job of the overloaded Edit method used for postbacks is to update the blog in the database with the data that came from the view.  A single line of code that leverages the DbContext.Entry method will make the context aware of the Blog and then tell the context that this Blog has been modified. By setting the State to Modified, you are instructing Entity Framework that it should construct an UPDATE command when you call SaveChanges in the next line of code.

  1. Modify the Edit HttpPost method to make the context aware of the Blog and then save it back to the database as follows:
[HttpPost]
        public ActionResult Edit(int id, Blog blog)
        {
          try
          {
            using (var db = new BlogModelContainer())
            {
              db.Entry(blog).State = System.Data.EntityState.Modified;
              db.SaveChanges();
              return RedirectToAction("Index");
            }
          }
          catch
          {
            return View();
          }
        }

Notice that just as you did for the Create method, you need to change the method signature to accept a Blog type instead of a FormCollection.

By default, the Edit view presents all of the properties except the key, Id.

 


Figure 19

After the changes are saved in the Edit postback method, MVC redirects back to the Index method. A fresh query is executed to retrieve the Blogs, including the newly updated Blog, which are then displayed in the Index view.

 


Figure 20

Deleting a Blog will work in much the same way.

Modify the Delete methods to match the following examples:

public ActionResult Delete(int id)
    {
      using (var db = new BlogModelContainer())
      {
        return View(db.Blogs.Find(id));
      }
    }
    [HttpPost]
    public ActionResult Delete(int id, Blog blog)
    {
      try
      {
        using (var db = new BlogModelContainer())
        {
          db.Entry(blog).State = System.Data.EntityState.Deleted;
          db.SaveChanges();
        }
        return RedirectToAction("Index");
      }
      catch
      {
        return View();
      }
    }

The first Delete method is just the same as its Edit counterpart. And the postback is similar to the Edit postback with one exception: you are setting the State to Delete rather than to Modified.

The Delete view presents a confirmation screen to the user.


Figure 21

When the user clicks the Delete button, the Delete postback method will be executed and the user will be returned to the Index view.

Summary

Entity Framework’s Model First is a great solution for creating new applications that do not have an existing database to work with. The Entity Data Model designer gives you a visual way to create your domain entities from which your domain classes can be automatically generated. Entity Framework’s DbContext templates and the DbContext class provide cleaner classes and a much simpler coding surface to write your data access code.

About the Author

Julie Lerman is a Microsoft MVP, .NET mentor and consultant who lives in the hills of Vermont. You can find her presenting on data access and other Microsoft .NET topics at user groups and conferences around the world. Julie blogs at  thedatafarm.com/blog and is the author of the highly acclaimed book, “Programming Entity Framework” (O’Reilly Media, 2009). Follow her on Twitter.com:  julielerman.

Microsoft is conducting an online survey to understand your opinion of the MSDN Web site. If you choose to participate, the online survey will be presented to you when you leave the MSDN Web site.

Would you like to participate?