Language

ASP.NET MVC 4 Entity Framework Scaffolding and Migrations

By Web Camps Team|

If you are familiar with ASP.NET MVC 4 controller methods, or have completed the "Helpers, Forms and Validation" Hands-On lab, you should be aware that many of the logic to create, update, list and remove any data entity it is repeated among the application. Not to mention that, if your model has several classes to manipulate, you will be likely to spend a considerable time writing the POST and GET action methods for each entity operation, as well as each of the views.

In this lab you will learn how to use the ASP.NET MVC 4 scaffolding to automatically generate the baseline of your application's CRUD (Create, Read, Update and Delete). Starting from a simple model class, and, without writing a single line of code, you will create a controller that will contain all the CRUD operations, as well as the all the necessary views. After building and running the simple solution, you will have the application database generated, together with the MVC logic and views for data manipulation.

In addition, you will learn how easy it is to use Entity Framework Migrations to perform model updates throughout your entire application. Entity Framework Migrations will let you modify your database after the model has changed with simple steps. With all these in mind, you will be able to build and maintain web applications more efficiently, taking advantage of the latest features of ASP.NET MVC 4.

Objectives

In this Hands-On Lab, you will learn how to:

  • Use ASP.NET scaffolding for CRUD operations in controllers.
  • Change the database model using Entity Framework Migrations.

Prerequisites

You must have the following items to complete this lab:

Setup

Installing Code Snippets

For convenience, much of the code you will be managing along this lab is available as Visual Studio code snippets. To install the code snippets run .\Source\Setup\CodeSnippets.vsi file.

If you are not familiar with the Visual Studio Code Snippets, and want to learn how to use them, you can refer to the appendix from this document "Appendix C: Using Code Snippets".


Exercises

The following exercise make up this Hands-On Lab:

  1. Using ASP.NET MVC 4 Scaffolding with Entity Framework Migrations

Note: This exercise is accompanied by an End folder containing the resulting solution you should obtain after completing the exercise. You can use this solution as a guide if you need additional help working through the exercise.

Estimated time to complete this lab: 30 minutes

Exercise 1: Using ASP.NET MVC 4 Scaffolding with Entity Framework Migrations

ASP.NET MVC scaffolding provides a quick way to generate the CRUD operations in a standardized way, creating the necessary logic that lets your application interact with the database layer.

In this exercise, you will learn how to use ASP.NET MVC 4 scaffolding with code first to create the CRUD methods. Then, you will learn how to update your model applying the changes in the database by using Entity Framework Migrations.

Task 1- Creating a new ASP.NET MVC 4 project using Scaffolding

  1. If not already open, start Visual Studio 2012.

  2. Select File | New Project. In the New Project dialog, under the Visual C# | Web section, select ASP.NET MVC 4 Web Application. Name the project to MVC4andEFMigrations and set the location to Source\Ex1-UsingMVC4ScaffoldingEFMigrations folder of this lab. Set the Solution name to Begin and ensure Create directory for solution is checked. Click OK.

    New ASP.NET MVC 4 Project Dialog Box

    New ASP.NET MVC 4 Project Dialog Box

  3. In the New ASP.NET MVC 4 Project dialog box select the Internet Application template, and make sure that Razor is the selected View engine. Click OK to create the project.

    New ASP.NET MVC 4 Internet Application

    New ASP.NET MVC 4 Internet Application

  4. In the Solution Explorer, right-click Models and select Add | Class to create a simple class person (POCO). Name it Person and click OK.

  5. Open the Person class and insert the following properties.

    (Code Snippet - ASP.NET MVC 4 and Entity Framework Migrations - Ex1 Person Properties)

    C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace MVC4EF.Models
    {
        public class Person
        {
            public int PersonID { get; set; }
    
            public string FirstName { get; set; }
    
            public string LastName { get; set; }        
        }
    }
    
  6. Click Build | Build Solution to save the changes and build the project.

    Building the application

    Building the Application

  7. In the Solution Explorer, right-click the controllers folder and select Add | Controller.

  8. Name the controller PersonController and complete the Scaffolding options with the following values.

    1. In the Template drop-down list, select the MVC controller with read/write actions and views, using Entity Framework option.
    2. In the Model class drop-down list, select the Person class.
    3. In the Data Context class list, select <New data context...>. Choose any name and click OK.
    4. In the Views drop-down list, make sure that Razor is selected.

    Adding the Person controller with scaffolding

    Adding the Person controller with scaffolding

  9. Click Add to create the new controller for Person with scaffolding. You have now generated the controller actions as well as the views.

    After creating the Person controller with scaffolding

    After creating the Person controller with scaffolding

  10. Open PersonController class. Notice that the full CRUD action methods have been generated automatically.

    Inside the Person controller

    Inside the Person controller

Task 2- Running the application

At this point, the database is not yet created. In this task, you will run the application for the first time and test the CRUD operations. The database will be created on the fly with Code First.

  1. Press F5 to run the application.

  2. In the browser, add /Person to the URL to open the Person page.

    Application first run

    Application: first run

  3. You will now explore the Person pages and test the CRUD operations.

    1. Click Create New to add a new person. Enter a first name and a last name and click Create.

      Adding a new person

      Adding a new person

    2. In the person's list, you can delete, edit or add items.

      person list

      Person list

    3. Click Details to open the person's details.

      Person's details

      Person's details

  4. Close the browser and return to Visual Studio. Notice that you have created the whole CRUD for the person entity throughout your application -from the model to the views- without having to write a single line of code!

Task 3- Updating the database using Entity Framework Migrations

In this task you will update the database using Entity Framework Migrations. You will discover how easy it is to change the model and reflect the changes in your databases by using the Entity Framework Migrations feature.

  1. Open the Package Manager Console. Select Tools | Library Package Manager | Package Manager Console.

  2. In the Package Manager Console, enter the following command:

    PMC
    Enable-Migrations -ContextTypeName [ContextClassName]
    
    
    

    Enabling Migrations

    Enabling migrations

    The Enable-Migration command creates the Migrations folder, which contains a script to initialize the database.

    Migrations folder

    Migrations folder

  3. Open the Configuration.cs file in the Migrations folder. Locate the class constructor and change the AutomaticMigrationsEnabled value to true.

    C#
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }
    
  4. Open the Person class and add an attribute for the person's middle name. With this new attribute, you are changing the model.

    C#
    public class 
    
    Person
    {
        public int PersonID { get; set; }
    
        public string FirstName { get; 
    
    set; }
    
        public string LastName { get; 
    
    set; }
    
        public string MiddleName { get; set; }
    }
    
  5. Select Build | Build Solution on the menu to build the application.

    Building the application

    Building the application

  6. In the Package Manager Console, enter the following command:

    PMC
    Add-Migration AddMiddleName
    

    This command will look for changes in the data objects, and then, it will add the necessary commands to modify the database accordingly.

    Adding a middle name

    Adding a middle name

  7. (Optional) You can run the following command to generate a SQL script with the differential update. This will let you update the database manually (In this case it's not necessary), or apply the changes in other databases:

    PMC
    Update-Database -Script -SourceMigration:
    
    $InitialDatabase
    

    Generating a SQL script

    Generating a SQL script

    SQL Script update

    SQL Script update

  8. In the Package Manager Console, enter the following command to update the database:

    PMC
    Update-Database -Verbose
    

    Updating the Database

    Updating the Database

    This will add the MiddleName column in the People table to match the current definition of the Person class.

  9. Once the database is updated, right-click the Controller folder and select Add | Controller to add the Person controller again (Complete with the same values). This will update the existing methods and views adding the new attribute.

    Adding a controller update

    Updating the controller

  10. Click Add. Then, select the values Overwrite PersonController.cs and the Overwrite associated views and click OK.

    Adding a controller overwrite

    Updating the controller

Task4- Running the application

  1. Press F5 to run the application.

  2. Open /Person. Notice that the data was preserved, while the middle name column was added.

    Middle Name added

    Middle Name added

  3. If you click Edit, you will be able to add a middle name to the current person.

    Middle Name edition

Note: Additionally, you can deploy this application to Windows Azure Web Sites following Appendix B: Publishing an ASP.NET MVC 4 Application using Web Deploy.


Summary

In this Hands-On lab, you have learned simple steps to create CRUD operations with ASP.NET MVC 4 Scaffolding using any model class. Then, you have learned how to perform an end to end update in your application -from the database to the views- by using Entity Framework Migrations.

Appendix A: Installing Visual Studio Express 2012 for Web

You can install Microsoft Visual Studio Express 2012 for Web or another "Express" version using the Microsoft Web Platform Installer. The following instructions guide you through the steps required to install Visual studio Express 2012 for Web using Microsoft Web Platform Installer.

  1. Go to http://go.microsoft.com/? linkid=9810169. Alternatively, if you already have installed Web Platform Installer, you can open it and search for the product "Visual Studio Express 2012 for Web with Windows Azure SDK".

  2. Click on Install Now. If you do not have Web Platform Installer you will be redirected to download and install it first.

  3. Once Web Platform Installer is open, click Install to start the setup.

    Install Visual Studio Express

    Install Visual Studio Express

  4. Read all the products' licenses and terms and click I Accept to continue.

    Accepting the license terms

    Accepting the license terms

  5. Wait until the downloading and installation process completes.

    Installation progress

    Installation progress

  6. When the installation completes, click Finish.

    Installation completed

    Installation completed

  7. Click Exit to close Web Platform Installer.

  8. To open Visual Studio Express for Web, go to the Start screen and start writing "VS Express", then click on the VS Express for Web tile.

    VS Express for Web tile

    VS Express for Web tile

Appendix B: Publishing an ASP.NET MVC 4 Application using Web Deploy

This appendix will show you how to create a new web site from the Windows Azure Management Portal and publish the application you obtained by following the lab, taking advantage of the Web Deploy publishing feature provided by Windows Azure.

Task 1 - Creating a New Web Site from the Windows Azure Portal

  1. Go to the Windows Azure Management Portal and sign in using the Microsoft credentials associated with your subscription.

    Note: With Windows Azure you can host 10 ASP.NET Web Sites for free and then scale as your traffic grows. You can sign up here.

    Log on to Windows Azure portal

    Log on to Windows Azure Management Portal

  2. Click New on the command bar.

    Creating a new Web Site

    Creating a new Web Site

  3. Click Compute | Web Site. Then select Quick Create option. Provide an available URL for the new web site and click Create Web Site.

    Note: A Windows Azure Web Site is the host for a web application running in the cloud that you can control and manage. The Quick Create option allows you to deploy a completed web application to the Windows Azure Web Site from outside the portal. It does not include steps for setting up a database.

    Creating a new Web Site using Quick Create

    Creating a new Web Site using Quick Create

  4. Wait until the new Web Site is created.

  5. Once the Web Site is created click the link under the URL column. Check that the new Web Site is working.

    Browsing to the new web site

    Browsing to the new web site

    Web site running

    Web site running

  6. Go back to the portal and click the name of the web site under the Name column to display the management pages.

    Opening the web site management pages

    Opening the Web Site management pages

  7. In the Dashboard page, under the quick glance section, click the Download publish profile link.

    Note: The publish profile contains all of the information required to publish a web application to a Windows Azure website for each enabled publication method. The publish profile contains the URLs, user credentials and database strings required to connect to and authenticate against each of the endpoints for which a publication method is enabled. Microsoft WebMatrix 2, Microsoft Visual Studio Express for Web and Microsoft Visual Studio 2012 support reading publish profiles to automate configuration of these programs for publishing web applications to Windows Azure websites.

    Downloading the web site publish profile

    Downloading the Web Site publish profile

  8. Download the publish profile file to a known location. Further in this exercise you will see how to use this file to publish a web application to a Windows Azure Web Sites from Visual Studio.

    Saving the publish profile file

    Saving the publish profile file

Task 2 - Configuring the Database Server

If your application makes use of SQL Server databases you will need to create a SQL Database server. If you want to deploy a simple application that does not use SQL Server you might skip this task.

  1. You will need a SQL Database server for storing the application database. You can view the SQL Database servers from your subscription in the Windows Azure Management portal at Sql Databases | Servers | Server's Dashboard. If you do not have a server created, you can create one using the Add button on the command bar. Take note of the server name and URL, administrator login name and password, as you will use them in the next tasks. Do not create the database yet, as it will be created in a later stage.

    SQL Database Server Dashboard

    SQL Database Server Dashboard

  2. In the next task you will test the database connection from Visual Studio, for that reason you need to include your local IP address in the server's list of Allowed IP Addresses. To do that, click Configure, select the IP address from Current Client IP Address and paste it on the Start IP Address and End IP Address text boxes and click the add-client-ip-address-ok-button button.

    Adding Client IP Address

    Adding Client IP Address

  3. Once the Client IP Address is added to the allowed IP addresses list, click on Save to confirm the changes.

    Confirm Changes

    Confirm Changes

Task 3 - Publishing an ASP.NET MVC 4 Application using Web Deploy

  1. Go back to the ASP.NET MVC 4 solution. In the Solution Explorer, right-click the web site project and select Publish.

    Publishing the Application

    Publishing the web site

  2. Import the publish profile you saved in the first task.

    Importing the publish profile

    Importing publish profile

  3. Click Validate Connection. Once Validation is complete click Next.

    Note: Validation is complete once you see a green checkmark appear next to the Validate Connection button.

    Validating connection

    Validating connection

  4. In the Settings page, under the Databases section, click the button next to your database connection's textbox (i.e. DefaultConnection).

    Web deploy configuration

    Web deploy configuration

  5. Configure the database connection as follows:

    • In the Server name type your SQL Database server URL using the tcp: prefix.
    • In User name type your server administrator login name.
    • In Password type your server administrator login password.
    • Type a new database name.

    Configuring destination connection string

    Configuring destination connection string

  6. Then click OK. When prompted to create the database click Yes.

    Creating the database

    Creating the database

  7. The connection string you will use to connect to SQL Database in Windows Azure is shown within Default Connection textbox. Then click Next.

    Connection string pointing to SQL Database

    Connection string pointing to SQL Database

  8. In the Preview page, click Publish.

    Publishing the web application

    Publishing the web application

  9. Once the publishing process finishes, your default browser will open the published web site.

Appendix C: Using Code Snippets

With code snippets, you have all the code you need at your fingertips. The lab document will tell you exactly when you can use them, as shown in the following figure.

Using Visual Studio code 

snippets to insert code into your project

Using Visual Studio code snippets to insert code into your project

To add a code snippet using the keyboard (C# only)

  1. Place the cursor where you would like to insert the code.

  2. Start typing the snippet name (without spaces or hyphens).

  3. Watch as IntelliSense displays matching snippets' names.

  4. Select the correct snippet (or keep typing until the entire snippet's name is selected).

  5. Press the Tab key twice to insert the snippet at the cursor location.

Start typing the snippet name

Start typing the snippet name

Press Tab to select the highlighted snippet

Press Tab to select the highlighted snippet

Press Tab again and the snippet will expand

Press Tab again and the snippet will expand

To add a code snippet using the mouse (C#, Visual Basic and XML) 1. Right-click where you want to insert the code snippet.

  1. Select Insert Snippet followed by My Code Snippets.

  2. Pick the relevant snippet from the list, by clicking on it.

Right-click where 

you want to insert the code snippet and select Insert Snippet

Right-click where you want to insert the code snippet and select Insert Snippet

Pick the relevant snippet from the 

list, by clicking on it

Pick the relevant snippet from the list, by clicking on it

This article was originally created on February 18, 2013

Author Information

Web Camps Team

Web Camps Team – Web Developer Camps are free, fun, no-fluff events for developers, by developers. You learn from experts in a low-key, interactive way and then get hands-on time to apply what you’ve learned. For more information on Web Camps, and to find one near you, visit http://www.devcamps.ms/web.

Comments (0) RSS Feed

Comments are closed.