Sunday, December 30, 2012

Creating an Entity Framework Data Model for an ASP.NET MVC Application (1 of 10)


Creating an Entity Framework Data Model for an ASP.NET MVC Application (1 of 10)

By Tom Dykstra|April 11, 2011
The Contoso University sample web application demonstrates how to create ASP.NET MVC 3 applications using the Entity Framework. The sample application is a website for a fictional Contoso University. It includes functionality such as student admission, course creation, and instructor assignments.
This tutorial series explains the steps taken to build the Contoso University sample application. You candownload the completed application or create it by following the steps in the tutorial. The tutorial shows examples in C#. The downloadable sample contains code in both C# and Visual Basic. If you have questions that are not directly related to the tutorial, you can post them to the ASP.NET Entity Framework forum or theEntity Framework and LINQ to Entities forum.
This tutorial series assumes you know how to work with ASP.NET MVC in Visual Studio. If you don’t, a good place to start is a basic ASP.NET MVC Tutorial. If you prefer to work with the ASP.NET Web Forms model, see the Getting Started with the Entity Framework and Continuing with the Entity Framework tutorials.
Before you start, make sure you have the following software installed on your computer:
Note: These tutorials were written for ASP.NET 4.1. The Code First Migrations feature was introduced in ASP.NET 4.3, so it isn't covered in these tutorials. Migrations solves the problem of what to do about data model changes after you have deployed your database to production. For a more recent tutorial that includes coverage of Code First Migrations, see Introduction to ASP.NET MVC 4 - Adding a New Field to the Movie Model and Table.

The Contoso University Web Application

The application you'll be building in these tutorials is a simple university website.
Contoso_University_home_page
Users can view and update student, course, and instructor information. A few of the screens you'll create are shown below.
Students_Index_page
Students_Create_page
Instructors_index_page
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.

Entity Framework Development Approaches

As shown in the following diagram, there are three ways you can work with data in the Entity Framework: Database FirstModel First, and Code First.
Development_approaches_diagram

Database First

If you already have a database, the Entity Framework can automatically generate a data model that consists of classes and properties that correspond to existing database objects such as tables and columns. The information about your database structure (store schema), your data model (conceptual model), and the mapping between them is stored in XML in an .edmx file. Visual Studio provides the Entity Framework designer, which is a graphical designer that you can use to display and edit the .edmx file. The sections Getting Started With the Entity Frameworkand Continuing With the Entity Framework in the Web Forms tutorial series use Database First development.

Model First

If you don't yet have a database, you can begin by creating a model using the Entity Framework designer in Visual Studio. When the model is finished, the designer can generate DDL (data definition language) statements to create the database. This approach also uses an .edmx file to store model and mapping information. The What's New in the Entity Framework 4 tutorial includes a brief example of Model First development.

Code First

Whether you have an existing database or not, you can code your own classes and properties that correspond to tables and columns and use them with the Entity Framework without an .edmx file. That's why you sometimes see this approach called code only, although the official name is Code First. The mapping between the store schema and the conceptual model represented by your code is handled by convention and by a special mapping API. If you don't yet have a database, the Entity Framework can automatically create the database for you, or drop and re-create it if the model changes. This tutorial series uses Code First development.
The data access API that was developed for Code First is based on the DbContext class. This API can also be used with the Database First and Model First development workflows. For more information, see When is Code First not code first? on the Entity Framework team blog.

POCO (Plain Old CLR Objects)

By default, when you use the Database First or Model First development approaches, the entity classes in your data model inherit from the EntityObject class, which provides them with Entity Framework functionality. This means that these classes technically aren't persistence ignorant and so don't conform fully to one of the requirements ofdomain-driven design. All development approaches of the Entity Framework can also work with POCO (plain old CLR objects) classes, which essentially means that they are persistence-ignorant because they don't inherit from theEntityObject class. In this tutorial you'll use POCO classes.

Creating an MVC Web Application

Before you start, make sure you have the following installed on your computer:
Open Visual Studio and create a new project named "ContosoUniversity" using the ASP.NET MVC 3 Web Application template:
New_project_dialog_box
In the New ASP.NET MVC 3 Project dialog box select the Internet Application template and the Razor view engine, clear the Create a unit test project check box, and then click OK.
Project_template_options

Setting Up the Site Style

A few simple changes will set up the site menu, layout, and home page.
In order to set up the Contoso University menu, in the Views\Shared\_Layout.cshtml file, replace the existing h1heading text and the menu links, as shown in the following example:
<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
</head>
<body>
    <div class="page">
       <div id="header">
            <div id="title">
                <h1>Contoso University</h1>
            </div>

            <div id="logindisplay">
                @Html.Partial("_LogOnPartial")
            </div>
            <div id="menucontainer">
                <ul id="menu">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Students", "Index", "Student")</li>
                    <li>@Html.ActionLink("Courses", "Index", "Course")</li>
                    <li>@Html.ActionLink("Instructors", "Index", "Instructor")</li>
                    <li>@Html.ActionLink("Departments", "Index", "Department")</li>
                </ul>
            </div>
        </div>
        <div id="main">
            @RenderBody()
        </div>
        <div id="footer">
        </div>
    </div>
</body>
</html>
In the Views\Home\Index.cshtml file, delete everything under the h2 heading.
In the Controllers\HomeController.cs file, replace "Welcome to ASP.NET MVC!" with "Welcome to Contoso University!"
In the Content\Site.css file, make the following changes in order to move the menu tabs to the left:
  • In the definition for #main, add clear: both;, as shown in the following example:
    #main 
    {
        clear: both;
        padding: 30px 30px 15px 30px;
        background-color: #fff;
        border-radius: 4px 0 0 0;
        -webkit-border-radius: 4px 0 0 0;
        -moz-border-radius: 4px 0 0 0;
    }
  • In the definition for nav and #menucontainer, add clear: both; float: left;, as shown in the following example:
    nav, #menucontainer {
        margin-top: 40px;
        clear: both;
        float: left;
    }
Run the site. You see the home page with the main menu.
Contoso_University_home_page

Creating the Data Model

Next you'll create your first entity classes for the Contoso University application. You'll start with the following three entities:
Class_diagram
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

Student_entity
In the Models folder, create Student.cs and replace the existing code with the following code:
using System;
using System.Collections.Generic;
namespace ContosoUniversity.Models
{
    public class Student
    {
        public int StudentID { get; set; }
        public string LastName { get; set; }
        public string FirstMidName { get; set; }
        public DateTime EnrollmentDate { get; set; }
        public virtual ICollection<Enrollment> Enrollments { get; set; }
    }
}
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 classnameID 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 Enrollmentrows (rows that contain that student's primary key value in their StudentID foreign key column), that Studententity's Enrollments navigation property will contain those two Enrollment entities.
Navigation properties are typically defined as virtual so that they can take advantage of an Entity Framework function called 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 ICollection.

The Enrollment Entity

Enrollment_entity
In the Models folder, create Enrollment.cs and replace the existing code with the following code:
using System;
using System.Collections.Generic;
namespace ContosoUniversity.Models
{
    public class Enrollment
    {
        public int EnrollmentID { get; set; }
        public int CourseID { get; set; }
        public int StudentID { get; set; }
        public decimal? Grade { get; set; }
        public virtual Course Course { get; set; }
        public virtual Student Student { get; set; }
    }
}
The question mark after the decimal type declaration indicates that the Grade property is nullable. A grade that's null is different from a zero grade — null means a grade hasn't been assigned yet, while zero means a zero grade has been assigned.
The StudentID property is a foreign key, and the corresponding navigation property is Student. An Enrollmententity is associated with one Student entity, so the property can only hold a single Student entity (unlike theStudent.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 Enrollmententity is associated with one Course entity.

The Course Entity

Course_entity
In the Models folder, create Course.cs, replacing the existing code with the following code:
using System;
using System.Collections.Generic;
namespace ContosoUniversity.Models
{
    public class Course
    {
        public int CourseID { get; set; }
        public string Title { get; set; }
        public int Credits { get; set; }
        public virtual ICollection<Enrollment> Enrollments { get; set; }
    }
}
The Enrollments property is a navigation property. A Course entity can be related to any number of Enrollmententities.

Creating 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 the code for this project, the class is named SchoolContext.
Create a DAL folder. In that folder create a new class file named SchoolContext.cs, and replace the existing code with the following code:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using ContosoUniversity.Models;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace ContosoUniversity.Models
{
    public class SchoolContext : DbContext
    {
        public DbSet<Student> Students { get; set; }
        public DbSet<Enrollment> Enrollments { get; set; }
        public DbSet<Course> Courses { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }
}
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 statement in the OnModelCreating method prevents table names from being pluralized. If you didn't do this, the generated tables would be named StudentsCourses, and Enrollments. Instead, the table names will beStudentCourse, 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.
(This class is in the Models namespace, because in some situations Code First assumes that the entity classes and the context class are in the same namespace.)

Setting the Connection String

You don't have to create a connection string. If you don't create one, the Entity Framework will automatically create a SQL Server Express database for you. In this tutorial, however, you'll work with SQL Server Compact, so you need to create a connection string to specify that.
Open the project 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 aWeb.config file is in the Views subfolder that you don't need to update. )
<add name="SchoolContext" connectionString="Data Source=|DataDirectory|School.sdf" providerName="System.Data.SqlServerCe.4.0"/>
By default, the Entity Framework looks for a connection string named the same as the object context class. The connection string you've added specifies a SQL Server Compact database named School.sdf located in the App_Datafolder.

Initializing the Database with Test Data

The Entity Framework can automatically create (or drop and re-create) a database for you when the application runs. You can specify that this should be done every time your application runs or only when the model is out of sync with the existing database. You can also write a class that includes a method that the Entity Framework automatically calls after creating the database in order to populate it with test data. In this section you'll specify that the database should be dropped and re-created whenever the model changes.
In the DAL folder, create a new class file named SchoolInitializer.cs and replace the existing code with the following code, which causes a database to be created when needed and loads test data into the new database.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using ContosoUniversity.Models;
namespace ContosoUniversity.DAL{
    public class SchoolInitializer : DropCreateDatabaseIfModelChanges<SchoolContext>
    {
        protected override void Seed(SchoolContext context)
        {
            var students = new List<Student>
            {
                new Student { FirstMidName = "Carson",   LastName = "Alexander", EnrollmentDate = DateTime.Parse("2005-09-01") },
                new Student { FirstMidName = "Meredith", LastName = "Alonso",    EnrollmentDate = DateTime.Parse("2002-09-01") },
                new Student { FirstMidName = "Arturo",   LastName = "Anand",     EnrollmentDate = DateTime.Parse("2003-09-01") },
                new Student { FirstMidName = "Gytis",    LastName = "Barzdukas", EnrollmentDate = DateTime.Parse("2002-09-01") },
                new Student { FirstMidName = "Yan",      LastName = "Li",        EnrollmentDate = DateTime.Parse("2002-09-01") },
                new Student { FirstMidName = "Peggy",    LastName = "Justice",   EnrollmentDate = DateTime.Parse("2001-09-01") },
                new Student { FirstMidName = "Laura",    LastName = "Norman",    EnrollmentDate = DateTime.Parse("2003-09-01") },
                new Student { FirstMidName = "Nino",     LastName = "Olivetto",  EnrollmentDate = DateTime.Parse("2005-09-01") }
            };
            students.ForEach(s => context.Students.Add(s));
            context.SaveChanges();

            var courses = new List<Course>
            {
                new Course { Title = "Chemistry",      Credits = 3, },
                new Course { Title = "Microeconomics", Credits = 3, },
                new Course { Title = "Macroeconomics", Credits = 3, },
                new Course { Title = "Calculus",       Credits = 4, },
                new Course { Title = "Trigonometry",   Credits = 4, },
                new Course { Title = "Composition",    Credits = 3, },
                new Course { Title = "Literature",     Credits = 4, }
            };
            courses.ForEach(s => context.Courses.Add(s));
            context.SaveChanges();

            var enrollments = new List<Enrollment>
            {
                new Enrollment { StudentID = 1, CourseID = 1, Grade = 1 },
                new Enrollment { StudentID = 1, CourseID = 2, Grade = 3 },
                new Enrollment { StudentID = 1, CourseID = 3, Grade = 1 },
                new Enrollment { StudentID = 2, CourseID = 4, Grade = 2 },
                new Enrollment { StudentID = 2, CourseID = 5, Grade = 4 },
                new Enrollment { StudentID = 2, CourseID = 6, Grade = 4 },
                new Enrollment { StudentID = 3, CourseID = 1            },
                new Enrollment { StudentID = 4, CourseID = 1,           },
                new Enrollment { StudentID = 4, CourseID = 2, Grade = 4 },
                new Enrollment { StudentID = 5, CourseID = 3, Grade = 3 },
                new Enrollment { StudentID = 6, CourseID = 4            },
                new Enrollment { StudentID = 7, CourseID = 5, Grade = 2 },
            };
            enrollments.ForEach(s => context.Enrollments.Add(s));
            context.SaveChanges();
        }
    }
}
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 theSaveChanges 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.
Make the following changes in the Global.asax.cs file to cause this initializer code to run when the application begins:
  • Add using statements:
    using System.Data.Entity;
    using ContosoUniversity.Models;
    using ContosoUniversity.DAL;
  • In the Application_Start method, call an Entity Framework method that runs the database initializer code:
     Database.SetInitializer<SchoolContext>(new SchoolInitializer());
The application is now set up so that when you access the database for the first time in a given run of the application, the Entity Framework compares the database to the model (your SchoolContext class). If there's a difference, the application drops and re-creates the database.
Note When you deploy an application to a production web server, you must remove code that seeds the database.
Now you'll create a web page to display data, and the process of requesting the data will automatically trigger the creation of the database. You'll begin by creating a new controller. But before you do that, build the project to make the model and context classes available to MVC controller scaffolding.

Creating a Student Controller

To create a Student controller, right-click the Controllers folder in Solution Explorer, select Add, and then clickController. In the Add Controller dialog box, make the following selections and then click Add:
  • Controller name: StudentController.
  • Template: Controller with read/write actions and views, using Entity Framework. (The default.)
  • 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.)
Add_Controller_dialog_box_for_Student_controller
Open the Controllers\StudentController.cs file. You see a class variable has been created that instantiates a database context object:
private SchoolContext db = new SchoolContext();
The Index action method gets a list of students from the Students property of the database context instance:
 public ViewResult Index()
{
    return View(db.Students.ToList());
}
The automatic scaffolding has also created a set of Student views. To customize the default headings and column order in the Index view, open Views\Student\Index.cshtml and replace the existing code with the following code:
@model IEnumerable<ContosoUniversity.Models.Student>

@{
    ViewBag.Title = "Students";
}
<h2>Students</h2>
<p>
    @Html.ActionLink("Create New", "Create")</p>
<table>
    <tr>
        <th></th>
        <th>Last Name</th>
        <th>First Name</th>
        <th>Enrollment Date</th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.StudentID }) |
            @Html.ActionLink("Details", "Details", new { id=item.StudentID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.StudentID })
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LastName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.FirstMidName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.EnrollmentDate)
        </td>
    </tr>
}
</table>
Run the site, click the Students tab, and you see a list of students.
Students_Index_page
Close the browser. In Solution Explorer, select the ContosoUniversity project (make sure the project and not the solution is selected). Click Show all Files if you aren't already in that mode. Click Refresh and then expand theApp_Data folder to see the School.sdf file.
School.sdf_file_in_Solution_Explorer
Double-click School.sdf to open Server Explorer. Then expand the Tables folder to see the tables that have been created in the database.
Note If you get an error when you double-click School.sdf, make sure you have installed Visual Studio 2010 SP1 Tools for SQL Server Compact 4.0. (For links to the software, see the list of prerequisites at the top of this page.) If you install the tools now, you'll have to close and re-open Visual Studio.
Server_Explorer_showing_School_tables
There's one table for each entity set, plus one additional table. The EdmMetadata table is used by the Entity Framework to determine when the model and the database are out of sync.
Right-click one of the tables and select Show Table Data to see the data that was loaded in the table by theSchoolInitializer class.
Table_data_in_Student_table
When you're finished, close the connection. (If you don't close the connection, you might get an error the next time you run the project).
Close_the_SQL_Compact_connection

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.
  • The Entity Framework connects to your database by looking for a connection string that has the same name as your context class (in this case, SchoolContext).
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.
You've now created a simple application that uses the Entity Framework and SQL Server Compact to store and display data. In the following tutorial you'll learn how to perform basic CRUD (create, read, update, delete) operations.

No comments:

Post a Comment