Note: A newer version is available. See the VS 2015, ASP.NET Core, and EF Core sample app.

Introduction

A Visual Studio 2013 project which shows how to use the Entity Framework 6 in an ASP.NET MVC 5 web application project, using the Code First development approach.

The previous version that uses EF 5 and MVC 4 in a Visual Studio 2012 project is available to download.

The code illustrates the following topics:

A tutorial series describes how to build the sample application from scratch. There is an EF 6 MVC 5 VS 2013 tutorial series and an EF 5 MVC 4 VS 2012 tutorial series.

Getting Started

To build and run this sample as-is, you must have Visual Studio 2013 or Visual Studio 2013 Express for Web installed. If you have Visual Studio 2015, change the connection string in the Web.config file so that the SQL Server instance name is MSSQLLocalDB instead of v11.0.

In most cases you can run the application by following these steps:

  1. Download and extract the .zip file.
  2. Open the solution file in Visual Studio.
  3. Build the solution, which automatically installs the missing NuGet packages.
  4. Open the Package Manager Console, and run the update-database command to create the database.
  5. Run the application.

If you have any problems with those instructions, follow these longer instructions.

  1. Download the .zip file.
  2. In File Explorer, right-click the .zip file and click Properties, then in the Properties window click Unblock.
  3. Unzip the file.
  4. Double-click the .sln file to launch Visual Studio.
  5. From the Tools menu, click Library Package Manager, then Package Manager Console.
  6. In the Package Manager Console (PMC), click Restore.
  7. Exit Visual Studio.
  8. Restart Visual Studio, opening the solution file you closed in the previous step.
  9. In the Package Manager Console (PMC), enter the Update-Database command. (If you get the following error:
    "The term 'Update-Database' is not recognized as the name of a cmdlet, function, script file, or operable program", exit and restart Visual Studio.)
  10. Each migration will run, then the seed method will run. You can now run the application.

Running the Sample

To run the sample, hit F5 or choose the Debug | Start Debugging menu command. You will see the home page which includes a menu bar. (In a narrow browser window you'll have to click the symbol at the top right of the page in order to see the menu.)

From this page you can select any of the tabs to perform various actions such as display a list of students, add new students, display a list of instructors, and so forth.

 

Source Code Overview

The ContosoUniversity folder includes the following folders and files