Creating an Entity Framework Data Model for an ASP.NET MVC Application (1 of 10)
by Tom Dykstra
[!NOTE]
A newer version of this tutorial series is available, for Visual Studio 2013, Entity Framework 6, and MVC 5.
The Contoso University sample web application demonstrates how to create ASP.NET MVC 4 applications using the Entity Framework 5 and Visual Studio 2012. The sample application is a web site for a fictional Contoso University. It includes functionality such as student admission, course creation, and instructor assignments. This tutorial series explains how to build the Contoso University sample application. You can download the completed application.
Code First
There are three ways you can work with data in the Entity Framework: Database First, Model First, and Code First. This tutorial is for Code First. For information about the differences between these workflows and guidance on how to choose the best one for your scenario, see Entity Framework Development Workflows.
MVC
The sample application is built on ASP.NET MVC. If you prefer to work with the ASP.NET Web Forms model, see the Model Binding and Web Forms tutorial series and ASP.NET Data Access Content Map.
Software versions
Shown in the tutorial Also works with Windows 8 Windows 7 Visual Studio 2012 Visual Studio 2012 Express for Web. This is automatically installed by the Windows Azure SDK if you don’t already have VS 2012 or VS 2012 Express for Web. Visual Studio 2013 should work, but the tutorial has not been tested with it, and some menu selections and dialog boxes are different. The VS 2013 version of the Windows Azure SDK is required for Windows Azure deployment. .NET 4.5 Most of the features shown will work in .NET 4, but some won’t. For example, enum support in EF requires .NET 4.5. Entity Framework 5 Windows Azure SDK 2.1 If you skip the Windows Azure deployment steps, you don’t need the SDK. When a new version of the SDK is released, the link will install the newer version. In that case, you might have to adapt some of the instructions to new UI and features. Questions
If you have questions that are not directly related to the tutorial, you can post them to the ASP.NET Entity Framework forum, the Entity Framework and LINQ to Entities forum, or StackOverflow.com.
Acknowledgments
See the last tutorial in the series for acknowledgments and a note about VB.
Original version of the tutorial
The original version of the tutorial is available in the the EF 4.1 / MVC 3 e-book.
The Contoso University Web Application
The 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.
Prerequisites
The 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 Application
Open 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 enum
properties, and that requires .NET 4.5).
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 Style
A few simple changes will set up the site menu, layout, and home page.
Open *Views\_Layout.cshtml*, and replace the contents of the file with the following code. The changes are highlighted.
[!code-cshtmlMain]
1: <!DOCTYPE html>
2: <html lang="en">
3: <head>
4: <meta charset="utf-8" />
5: <title>@ViewBag.Title - Contoso University</title>
6: <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
7: <meta name="viewport" content="width=device-width" />
8: @Styles.Render("~/Content/css")
9: @Scripts.Render("~/bundles/modernizr")
10: </head>
11: <body>
12: <header>
13: <div class="content-wrapper">
14: <div class="float-left">
15: <p class="site-title">@Html.ActionLink("Contoso University", "Index", "Home")</p>
16: </div>
17: <div class="float-right">
18: <section id="login">
19: @Html.Partial("_LoginPartial")
20: </section>
21: <nav>
22: <ul id="menu">
23: <li>@Html.ActionLink("Home", "Index", "Home")</li>
24: <li>@Html.ActionLink("About", "About", "Home")</li>
25: <li>@Html.ActionLink("Students", "Index", "Student")</li>
26: <li>@Html.ActionLink("Courses", "Index", "Course")</li>
27: <li>@Html.ActionLink("Instructors", "Index", "Instructor")</li>
28: <li>@Html.ActionLink("Departments", "Index", "Department")</li>
29: </ul>
30: </nav>
31: </div>
32: </div>
33: </header>
34: <div id="body">
35: @RenderSection("featured", required: false)
36: <section class="content-wrapper main-content clear-fix">
37: @RenderBody()
38: </section>
39: </div>
40: <footer>
41: <div class="content-wrapper">
42: <div class="float-left">
43: <p>© @DateTime.Now.Year - Contoso University</p>
44: </div>
45: </div>
46: </footer>
47:
48: @Scripts.Render("~/bundles/jquery")
49: @RenderSection("scripts", required: false)
50: </body>
51: </html>
This code makes the following changes:
- Replaces the template instances of “My ASP.NET MVC Application” and “your logo here” with “Contoso University”.
- Adds several action links that will be used later in the tutorial.
In Views.cshtml, replace the contents of the file with the following code to eliminate the template paragraphs about ASP.NET and MVC:
[!code-cshtmlMain]
1: @{
2: ViewBag.Title = "Home Page";
3: }
4: @section featured {
5: <section class="featured">
6: <div class="content-wrapper">
7: <hgroup class="title">
8: <h1>@ViewBag.Title.</h1>
9: <h2>@ViewBag.Message</h2>
10: </hgroup>
11: </div>
12: </section>
13: }
In Controllers.cs, change the value for ViewBag.Message
in the Index
Action method to “Welcome to Contoso University!”, as shown in the following example:
[!code-csharpMain]
1: public ActionResult Index()
2: {
3: ViewBag.Message = "Welcome to Contoso University";
4:
5: return View();
6: }
Press CTRL+F5 to run the site. You see the home page with the main menu.
Create the Data Model
Next 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 Student
and Enrollment
entities, and there’s a one-to-many relationship between Course
and Enrollment
entities. In other words, a student can be enrolled in any number of courses, and a course can have any number of students enrolled in it.
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 Entity
In the Models folder, create Student.cs and replace the existing code with the following code:
[!code-csharpMain]
1: using System;
2: using System.Collections.Generic;
3:
4: namespace ContosoUniversity.Models
5: {
6: public class Student
7: {
8: public int StudentID { get; set; }
9: public string LastName { get; set; }
10: public string FirstMidName { get; set; }
11: public DateTime EnrollmentDate { get; set; }
12:
13: public virtual ICollection<Enrollment> Enrollments { get; set; }
14: }
15: }
The StudentID
property will become the primary key column of the database table that corresponds to this class. By default, the Entity Framework interprets a property that’s named ID
or classname ID
as the primary key.
The Enrollments
property is a navigation property. Navigation properties hold other entities that are related to this entity. In this case, the Enrollments
property of a Student
entity will hold all of the Enrollment
entities that are related to that Student
entity. In other words, if a given Student
row in the database has two related Enrollment
rows (rows that contain that student’s primary key value in their StudentID
foreign key column), that Student
entity’s Enrollments
navigation property will contain those two Enrollment
entities.
Navigation properties are typically defined as virtual
so that they can take advantage of certain Entity Framework functionality such as lazy loading. (Lazy loading will be explained later, in the Reading Related Data tutorial later in this series.
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 ICollection
.
The Enrollment Entity
In the Models folder, create Enrollment.cs and replace the existing code with the following code:
[!code-csharpMain]
1: namespace ContosoUniversity.Models
2: {
3: public enum Grade
4: {
5: A, B, C, D, F
6: }
7:
8: public class Enrollment
9: {
10: public int EnrollmentID { get; set; }
11: public int CourseID { get; set; }
12: public int StudentID { get; set; }
13: public Grade? Grade { get; set; }
14:
15: public virtual Course Course { get; set; }
16: public virtual Student Student { get; set; }
17: }
18: }
The Grade property is an enum. The question mark after the Grade
type declaration indicates that the Grade
property is nullable. A grade that’s null is different from a zero grade — null means a grade isn’t known or hasn’t been assigned yet.
The StudentID
property is a foreign key, and the corresponding navigation property is Student
. An Enrollment
entity is associated with one Student
entity, so the property can only hold a single Student
entity (unlike the Student.Enrollments
navigation property you saw earlier, which can hold multiple Enrollment
entities).
The CourseID
property is a foreign key, and the corresponding navigation property is Course
. An Enrollment
entity is associated with one Course
entity.
The Course Entity
In the Models folder, create Course.cs, replacing the existing code with the following code:
[!code-csharpMain]
1: using System.Collections.Generic;
2: using System.ComponentModel.DataAnnotations.Schema;
3:
4: namespace ContosoUniversity.Models
5: {
6: public class Course
7: {
8: [DatabaseGenerated(DatabaseGeneratedOption.None)]
9: public int CourseID { get; set; }
10: public string Title { get; set; }
11: public int Credits { get; set; }
12:
13: public virtual ICollection<Enrollment> Enrollments { get; set; }
14: }
15: }
The Enrollments
property is a navigation property. A Course
entity can be related to any number of Enrollment
entities.
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 Context
The 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 SchoolContext
.
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:
[!code-csharpMain]
1: using ContosoUniversity.Models;
2: using System.Data.Entity;
3: using System.Data.Entity.ModelConfiguration.Conventions;
4:
5: namespace ContosoUniversity.DAL
6: {
7: public class SchoolContext : DbContext
8: {
9: public DbSet<Student> Students { get; set; }
10: public DbSet<Enrollment> Enrollments { get; set; }
11: public DbSet<Course> Courses { get; set; }
12:
13: protected override void OnModelCreating(DbModelBuilder modelBuilder)
14: {
15: modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
16: }
17: }
18: }
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 modelBuilder.Conventions.Remove
statement in the OnModelCreating method prevents table names from being pluralized. If you didn’t do this, the generated tables would be named Students
, Courses
, and Enrollments
. Instead, the table names will be Student
, Course
, and Enrollment
. Developers disagree about whether table names should be pluralized or not. This tutorial uses the singular form, but the important point is that you can select whichever form you prefer by including or omitting this line of code.
SQL Server Express LocalDB
LocalDB 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 connectionStrings
collection, as shown in the following example. (Make sure you update the Web.config file in the root project folder. There’s also a Web.config file is in the Views subfolder that you don’t need to update.)
[!code-xmlMain]
1: <add name="SchoolContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=ContosoUniversity;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\ContosoUniversity.mdf" providerName="System.Data.SqlClient" />
By default, the Entity Framework looks for a connection string named the same as the DbContext
class (SchoolContext
for this project). The connection string you’ve added specifies a LocalDB database named ContosoUniversity.mdf located in the App_Data folder. For more information, see SQL Server Connection Strings for ASP.NET Web Applications.
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 connectionStrings
collection also has a connection string named DefaultConnection
which is used for the membership database. You won’t be using the membership database in this tutorial. The only difference between the two connection strings is the database name and the name attribute value.
Set up and Execute a Code First Migration
When 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
From the Tools menu, click Library Package Manager and then Package Manager Console.
At the
PM>
prompt enter the following command:[!code-powershellMain]
1: enable-migrations -contexttypename SchoolContext
This command creates a Migrations folder in the ContosoUniversity project, and it puts in that folder a Configuration.cs file that you can edit to configure Migrations.
The
Configuration
class includes aSeed
method that is called when the database is created and every time it is updated after a data model change.[!code-csharpMain]
1: internal sealed class Configuration : DbMigrationsConfiguration<ContosoUniversity.Models.SchoolContext>
2: {
3: public Configuration()
4: {
5: AutomaticMigrationsEnabled = false;
6: }
7:
8: protected override void Seed(ContosoUniversity.Models.SchoolContext context)
9: {
10: // This method will be called after migrating to the latest version.
11:
12: // You can use the DbSet<T>.AddOrUpdate() helper extension method
13: // to avoid creating duplicate seed data. E.g.
14: //
15: // context.People.AddOrUpdate(
16: // p => p.FullName,
17: // new Person { FullName = "Andrew Peters" },
18: // new Person { FullName = "Brice Lambson" },
19: // new Person { FullName = "Rowan Miller" }
20: // );
21: //
22: }
23: }
The purpose of this
Seed
method is to enable you to insert test data into the database after Code First creates it or updates it.
Set up the Seed Method
The 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 Seed
methods to insert test data, because with every model change during development the database had to be completely deleted and re-created from scratch. With Code First Migrations, test data is retained after database changes, so including test data in the Seed method is typically not necessary. In fact, you don’t want the Seed
method to insert test data if you’ll be using Migrations to deploy the database to production, because the Seed
method will run in production. In that case you want the Seed
method to insert into the database only the data that you want to be inserted in production. For example, you might want the database to include actual department names in the Department
table when the application becomes available in production.
For this tutorial, you’ll be using Migrations for deployment, but your Seed
method will insert test data anyway in order to make it easier to see how application functionality works without having to manually insert a lot of data.
Replace the contents of the Configuration.cs file with the following code, which will load test data into the new database.
[!code-csharpMain]
1: namespace ContosoUniversity.Migrations
2: {
3: using System;
4: using System.Collections.Generic;
5: using System.Data.Entity.Migrations;
6: using System.Linq;
7: using ContosoUniversity.Models;
8:
9: internal sealed class Configuration : DbMigrationsConfiguration<ContosoUniversity.DAL.SchoolContext>
10: {
11: public Configuration()
12: {
13: AutomaticMigrationsEnabled = false;
14: }
15:
16: protected override void Seed(ContosoUniversity.DAL.SchoolContext context)
17: {
18: var students = new List<Student>
19: {
20: new Student { FirstMidName = "Carson", LastName = "Alexander",
21: EnrollmentDate = DateTime.Parse("2010-09-01") },
22: new Student { FirstMidName = "Meredith", LastName = "Alonso",
23: EnrollmentDate = DateTime.Parse("2012-09-01") },
24: new Student { FirstMidName = "Arturo", LastName = "Anand",
25: EnrollmentDate = DateTime.Parse("2013-09-01") },
26: new Student { FirstMidName = "Gytis", LastName = "Barzdukas",
27: EnrollmentDate = DateTime.Parse("2012-09-01") },
28: new Student { FirstMidName = "Yan", LastName = "Li",
29: EnrollmentDate = DateTime.Parse("2012-09-01") },
30: new Student { FirstMidName = "Peggy", LastName = "Justice",
31: EnrollmentDate = DateTime.Parse("2011-09-01") },
32: new Student { FirstMidName = "Laura", LastName = "Norman",
33: EnrollmentDate = DateTime.Parse("2013-09-01") },
34: new Student { FirstMidName = "Nino", LastName = "Olivetto",
35: EnrollmentDate = DateTime.Parse("2005-08-11") }
36: };
37: students.ForEach(s => context.Students.AddOrUpdate(p => p.LastName, s));
38: context.SaveChanges();
39:
40: var courses = new List<Course>
41: {
42: new Course {CourseID = 1050, Title = "Chemistry", Credits = 3, },
43: new Course {CourseID = 4022, Title = "Microeconomics", Credits = 3, },
44: new Course {CourseID = 4041, Title = "Macroeconomics", Credits = 3, },
45: new Course {CourseID = 1045, Title = "Calculus", Credits = 4, },
46: new Course {CourseID = 3141, Title = "Trigonometry", Credits = 4, },
47: new Course {CourseID = 2021, Title = "Composition", Credits = 3, },
48: new Course {CourseID = 2042, Title = "Literature", Credits = 4, }
49: };
50: courses.ForEach(s => context.Courses.AddOrUpdate(p => p.Title, s));
51: context.SaveChanges();
52:
53: var enrollments = new List<Enrollment>
54: {
55: new Enrollment {
56: StudentID = students.Single(s => s.LastName == "Alexander").StudentID,
57: CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID,
58: Grade = Grade.A
59: },
60: new Enrollment {
61: StudentID = students.Single(s => s.LastName == "Alexander").StudentID,
62: CourseID = courses.Single(c => c.Title == "Microeconomics" ).CourseID,
63: Grade = Grade.C
64: },
65: new Enrollment {
66: StudentID = students.Single(s => s.LastName == "Alexander").StudentID,
67: CourseID = courses.Single(c => c.Title == "Macroeconomics" ).CourseID,
68: Grade = Grade.B
69: },
70: new Enrollment {
71: StudentID = students.Single(s => s.LastName == "Alonso").StudentID,
72: CourseID = courses.Single(c => c.Title == "Calculus" ).CourseID,
73: Grade = Grade.B
74: },
75: new Enrollment {
76: StudentID = students.Single(s => s.LastName == "Alonso").StudentID,
77: CourseID = courses.Single(c => c.Title == "Trigonometry" ).CourseID,
78: Grade = Grade.B
79: },
80: new Enrollment {
81: StudentID = students.Single(s => s.LastName == "Alonso").StudentID,
82: CourseID = courses.Single(c => c.Title == "Composition" ).CourseID,
83: Grade = Grade.B
84: },
85: new Enrollment {
86: StudentID = students.Single(s => s.LastName == "Anand").StudentID,
87: CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID
88: },
89: new Enrollment {
90: StudentID = students.Single(s => s.LastName == "Anand").StudentID,
91: CourseID = courses.Single(c => c.Title == "Microeconomics").CourseID,
92: Grade = Grade.B
93: },
94: new Enrollment {
95: StudentID = students.Single(s => s.LastName == "Barzdukas").StudentID,
96: CourseID = courses.Single(c => c.Title == "Chemistry").CourseID,
97: Grade = Grade.B
98: },
99: new Enrollment {
100: StudentID = students.Single(s => s.LastName == "Li").StudentID,
101: CourseID = courses.Single(c => c.Title == "Composition").CourseID,
102: Grade = Grade.B
103: },
104: new Enrollment {
105: StudentID = students.Single(s => s.LastName == "Justice").StudentID,
106: CourseID = courses.Single(c => c.Title == "Literature").CourseID,
107: Grade = Grade.B
108: }
109: };
110:
111: foreach (Enrollment e in enrollments)
112: {
113: var enrollmentInDataBase = context.Enrollments.Where(
114: s =>
115: s.Student.StudentID == e.StudentID &&
116: s.Course.CourseID == e.CourseID).SingleOrDefault();
117: if (enrollmentInDataBase == null)
118: {
119: context.Enrollments.Add(e);
120: }
121: }
122: context.SaveChanges();
123: }
124: }
125: }
The Seed method takes the database context object as an input parameter, and the code in the method uses that object to add new entities to the database. For each entity type, the code creates a collection of new entities, adds them to the appropriate DbSet property, and then saves the changes to the database. It isn’t necessary to call the SaveChanges method after each group of entities, as is done here, but doing that helps you locate the source of a problem if an exception occurs while the code is writing to the database.
Some of the statements that insert data use the AddOrUpdate method to perform an “upsert” operation. Because the
Seed
method runs with every migration, you can’t just insert data, because the rows you are trying to add will already be there after the first migration that creates the database. The “upsert” operation prevents errors that would happen if you try to insert a row that already exists, but it overrides any changes to data that you may have made while testing the application. With test data in some tables you might not want that to happen: in some cases when you change data while testing you want your changes to remain after database updates. In that case you want to do a conditional insert operation: insert a row only if it doesn’t already exist. The Seed method uses both approaches.The first parameter passed to the AddOrUpdate method specifies the property to use to check if a row already exists. For the test student data that you are providing, the
LastName
property can be used for this purpose since each last name in the list is unique:[!code-csharpMain]
1: context.Students.AddOrUpdate(p => p.LastName, s)
This code assumes that last names are unique. If you manually add a student with a duplicate last name, you’ll get the following exception the next time you perform a migration.
Sequence contains more than one element
For more information about the
AddOrUpdate
method, see Take care with EF 4.3 AddOrUpdate Method on Julie Lerman’s blog.The code that adds
Enrollment
entities doesn’t use theAddOrUpdate
method. It checks if an entity already exists and inserts the entity if it doesn’t exist. This approach will preserve changes you make to an enrollment grade when migrations run. The code loops through each member of theEnrollment
List and if the enrollment is not found in the database, it adds the enrollment to the database. The first time you update the database, the database will be empty, so it will add each enrollment.[!code-csharpMain]
1: foreach (Enrollment e in enrollments)
2: {
3: var enrollmentInDataBase = context.Enrollments.Where(
4: s => s.Student.StudentID == e.Student.StudentID &&
5: s.Course.CourseID == e.Course.CourseID).SingleOrDefault();
6: if (enrollmentInDataBase == null)
7: {
8: context.Enrollments.Add(e);
9: }
10: }
Seed
method and how to handle redundant data such as two students named “Alexander Carson”, see Seeding and Debugging Entity Framework (EF) DBs on Rick Anderson’s blog.Build the project.
Create and Execute the First Migration
In the Package Manager Console window, enter the following commands:
[!code-powershellMain]
1: add-migration InitialCreate
2: update-database
The
add-migration
command adds to the Migrations folder a [DateStamp]_InitialCreate.cs file that contains code which creates the database. The first parameter (InitialCreate)
is used for the file name and can be whatever you want; you typically choose a word or phrase that summarizes what is being done in the migration. For example, you might name a later migration “AddDepartmentTable”.The
Up
method of theInitialCreate
class creates the database tables that correspond to the data model entity sets, and theDown
method deletes them. Migrations calls theUp
method to implement the data model changes for a migration. When you enter a command to roll back the update, Migrations calls theDown
method. The following code shows the contents of theInitialCreate
file:[!code-csharpMain]
1: namespace ContosoUniversity.Migrations
2: {
3: using System;
4: using System.Data.Entity.Migrations;
5:
6: public partial class InitialCreate : DbMigration
7: {
8: public override void Up()
9: {
10: CreateTable(
11: "dbo.Student",
12: c => new
13: {
14: StudentID = c.Int(nullable: false, identity: true),
15: LastName = c.String(),
16: FirstMidName = c.String(),
17: EnrollmentDate = c.DateTime(nullable: false),
18: })
19: .PrimaryKey(t => t.StudentID);
20:
21: CreateTable(
22: "dbo.Enrollment",
23: c => new
24: {
25: EnrollmentID = c.Int(nullable: false, identity: true),
26: CourseID = c.Int(nullable: false),
27: StudentID = c.Int(nullable: false),
28: Grade = c.Int(),
29: })
30: .PrimaryKey(t => t.EnrollmentID)
31: .ForeignKey("dbo.Course", t => t.CourseID, cascadeDelete: true)
32: .ForeignKey("dbo.Student", t => t.StudentID, cascadeDelete: true)
33: .Index(t => t.CourseID)
34: .Index(t => t.StudentID);
35:
36: CreateTable(
37: "dbo.Course",
38: c => new
39: {
40: CourseID = c.Int(nullable: false),
41: Title = c.String(),
42: Credits = c.Int(nullable: false),
43: })
44: .PrimaryKey(t => t.CourseID);
45:
46: }
47:
48: public override void Down()
49: {
50: DropIndex("dbo.Enrollment", new[] { "StudentID" });
51: DropIndex("dbo.Enrollment", new[] { "CourseID" });
52: DropForeignKey("dbo.Enrollment", "StudentID", "dbo.Student");
53: DropForeignKey("dbo.Enrollment", "CourseID", "dbo.Course");
54: DropTable("dbo.Course");
55: DropTable("dbo.Enrollment");
56: DropTable("dbo.Student");
57: }
58: }
59: }
The
update-database
command runs theUp
method to create the database and then it runs theSeed
method to populate the database.
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.
- From the View menu, click Server Explorer.
Click the Add Connection icon.
If you are prompted with the Choose Data Source dialog, click Microsoft SQL Server, and then click Continue.
- In the Add Connection dialog box, enter **(localdb)
- Click OK.
Expand SchoolContext and then expand Tables.
Right-click the Student table and click Show Table Data to see the columns that were created and the rows that were inserted into the table.
Creating a Student Controller and Views
The next step is to create an ASP.NET MVC controller and views in your application that can work with one of these tables.
To create a
Student
controller, right-click the Controllers folder in Solution Explorer, select Add, and then click Controller. In the Add Controller dialog box, make the following selections and then click Add:- Controller name: StudentController.
- Template: MVC controller with read/write actions and views, using Entity Framework.
- Model class: Student (ContosoUniversity.Models). (If you don’t see this option in the drop-down list, build the project and try again.)
- Data context class: SchoolContext (ContosoUniversity.Models).
- Views: Razor (CSHTML). (The default.)
Visual Studio opens the Controllers.cs file. You see a class variable has been created that instantiates a database context object:
[!code-csharpMain]
1: private SchoolContext db = new SchoolContext();
The
Index
action method gets a list of students from the Students entity set by reading theStudents
property of the database context instance:[!code-csharpMain]
1: public ViewResult Index()
2: {
3: return View(db.Students.ToList());
4: }
The Student.cshtml view displays this list in a table:
[!code-cshtmlMain]1: <table>
2: <tr>
3: <th>
4: @Html.DisplayNameFor(model => model.LastName)
5: </th>
6: <th>
7: @Html.DisplayNameFor(model => model.FirstMidName)
8: </th>
9: <th>
10: @Html.DisplayNameFor(model => model.EnrollmentDate)
11: </th>
12: <th></th>
13: </tr>
14:
15: @foreach (var item in Model) {
16: <tr>
17: <td>
18: @Html.DisplayFor(modelItem => item.LastName)
19: </td>
20: <td>
21: @Html.DisplayFor(modelItem => item.FirstMidName)
22: </td>
23: <td>
24: @Html.DisplayFor(modelItem => item.EnrollmentDate)
25: </td>
26: <td>
27: @Html.ActionLink("Edit", "Edit", new { id=item.StudentID }) |
28: @Html.ActionLink("Details", "Details", new { id=item.StudentID }) |
29: @Html.ActionLink("Delete", "Delete", new { id=item.StudentID })
30: </td>
31: </tr>
32: }
Press CTRL+F5 to run the project.
Click the Students tab to see the test data that the
Seed
method inserted.
Conventions
The 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:
- The pluralized forms of entity class names are used as table names.
- Entity property names are used for column names.
- Entity properties that are named
ID
or classnameID
are recognized as primary key properties.
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.
Summary
You’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.
|