Skip to main content This browser is no longer supported. Show
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support. Creating an Entity Framework Data Model for an ASP.NET MVC Application (1 of 10)
In this articleby Tom Dykstra
The Contoso University Web ApplicationThe application you'll be building in these tutorials is a simple university web site. Users can view and update student, course, and instructor information. Here are a few of the screens you'll create. The UI style of this site has been kept close to what's generated by the built-in templates, so that the tutorial can focus mainly on how to use the Entity Framework. PrerequisitesThe directions and screen shots in this tutorial assume that you're using Visual Studio 2012 or Visual Studio 2012 Express for Web, with the latest update and Azure SDK for .NET installed as of July, 2013. You can get all of this with the following link: Azure SDK for .NET (Visual Studio 2012) If you have Visual Studio installed, the link above will install any missing components. If you don't have Visual Studio, the link will install Visual Studio 2012 Express for Web. You can use Visual Studio 2013, but some of the required procedures and screens will differ. Create an MVC Web ApplicationOpen Visual Studio and create a new C# project named "ContosoUniversity" using the ASP.NET MVC 4 Web Application template. Make sure you target .NET Framework 4.5 (you'll be using In the New ASP.NET MVC 4 Project dialog box select the Internet Application template. Leave the Razor view engine selected, and leave the Create a unit test project check box cleared. Click OK. Set Up the Site StyleA few simple changes will set up the site menu, layout, and home page. Open Views\Shared\_Layout.cshtml, and replace the contents of the file with the following code. The changes are highlighted.
This code makes the following changes:
In Views\Home\Index.cshtml, replace the contents of the file with the following code to eliminate the template paragraphs about ASP.NET and MVC:
In Controllers\HomeController.cs, change the value for
Press CTRL+F5 to run the site. You see the home page with the main menu. Create the Data ModelNext you'll create entity classes for the Contoso University application. You'll start with the following three entities: There's a one-to-many relationship between In the following sections you'll create a class for each one of these entities. Note If you try to compile the project before you finish creating all of these entity classes, you'll get compiler errors. The Student EntityIn the Models folder, create Student.cs and replace the existing code with the following code:
The The Navigation properties are typically defined as If a navigation property can hold multiple entities (as in many-to-many or one-to-many relationships), its type must be a list in which entries can be added, deleted, and updated, such as
The Enrollment EntityIn the Models folder, create Enrollment.cs and replace the existing code with the following code:
The Grade property is an
enum. The question mark after the The The The Course EntityIn the Models folder, create Course.cs, replacing the existing code with the following code:
The We'll say more about the [DatabaseGenerated(DatabaseGeneratedOption.None)] attribute in the next tutorial. Basically, this attribute lets you enter the primary key for the course rather than having the database generate it. Create the Database ContextThe main class that coordinates Entity Framework functionality for a given data model is the database context class. You create this class by deriving from the System.Data.Entity.DbContext
class. In your code you specify which entities are included in the data model. You can also customize certain Entity Framework behavior. In this project, the class is named Create a folder named DAL (for Data Access Layer). In that folder create a new class file named SchoolContext.cs, and replace the existing code with the following code:
This code creates a DbSet property for each entity set. In Entity Framework terminology, an entity set typically corresponds to a database table, and an entity corresponds to a row in the table. The SQL Server Express LocalDBLocalDB is a lightweight version of the SQL Server Express Database Engine that starts on demand and runs in user mode. LocalDB runs in a special execution mode of SQL Server Express that enables you to work with databases as .mdf files. Typically, LocalDB database files are kept in the App_Data folder of a web project. The user instance feature in SQL Server Express also enables you to work with .mdf files, but the user instance feature is deprecated; therefore, LocalDB is recommended for working with .mdf files. Typically SQL Server Express is not used for production web applications. LocalDB in particular is not recommended for production use with a web application because it is not designed to work with IIS. In Visual Studio 2012 and later versions, LocalDB is installed by default with Visual Studio. In Visual Studio 2010 and earlier versions, SQL Server Express (without LocalDB) is installed by default with Visual Studio; you have to install it manually if you're using Visual Studio 2010. In this tutorial you'll work with LocalDB so that the database can be stored in the
App_Data folder as an .mdf file. Open the root Web.config file and add a new connection string to the
By default, the Entity Framework looks for a connection string named the same as the You don't actually need to specify the connection string. If you don't supply a connection string, Entity Framework will create one for you; however, the database might not be in the App_data folder of your app. For information on where the database will be created, see Code First to a New Database. The Set up and Execute a Code First MigrationWhen you first start to develop an application, your data model changes frequently, and each time the model changes it gets out of sync with the database. You can configure the Entity Framework to automatically drop and re-create the database each time you change the data model. This is not a problem early in development because test data is easily re-created, but after you have deployed to production you usually want to update the database schema without dropping the database. The Migrations feature enables Code First to update the database without dropping and re-creating it. Early in the development cycle of a new project you might want to use DropCreateDatabaseIfModelChanges to drop, recreate and re-seed the database each time the model changes. One you get ready to deploy your application, you can convert to the migrations approach. For this tutorial you'll only use migrations. For more information, see Code First Migrations and Migrations Screencast Series. Enable Code First Migrations
Set up the Seed MethodThe Seed method runs when Code First Migrations creates the database and every time it updates the database to the latest migration. The purpose of the Seed method is to enable you to insert data into your tables before the application accesses the database for the first time. In earlier versions of Code First, before Migrations was released, it was common for For this tutorial, you'll be using Migrations for deployment, but your
Create and Execute the First Migration
A SQL Server database has now been created for your data model. The name of the database is ContosoUniversity, and the .mdf file is in your project's App_Data folder because that's what you specified in your connection string. You can use either Server Explorer or SQL Server Object Explorer (SSOX) to view the database in Visual Studio. For this tutorial you'll use Server Explorer. In Visual Studio Express 2012 for Web, Server Explorer is called Database Explorer.
Creating a Student Controller and ViewsThe next step is to create an ASP.NET MVC controller and views in your application that can work with one of these tables.
ConventionsThe amount of code you had to write in order for the Entity Framework to be able to create a complete database for you is minimal because of the use of conventions, or assumptions that the Entity Framework makes. Some of them have already been noted:
You've seen that conventions can be overridden (for example, you specified that table names shouldn't be pluralized), and you'll learn more about conventions and how to override them in the Creating a More Complex Data Model tutorial later in this series. For more information, see Code First Conventions. SummaryYou've now created a simple application that uses the Entity Framework and SQL Server Express to store and display data. In the following tutorial you'll learn how to perform basic CRUD (create, read, update, delete) operations. You can leave feedback at the bottom of this page. Please let us know how you liked this portion of the tutorial and how we could improve it. Links to other Entity Framework resources can be found in the ASP.NET Data Access Content Map. |