Getting Started With Entity Framework 6 Database First Using MVC 5
Getting Started With Entity Framework 6 Database First Using MVC 5
NET MVC
1. Introduction
This topic shows how to start with an existing database and quickly create a web application that
enables users to interact with the data. It uses the Entity Framework 6 and MVC 5 to build the
web application. The ASP.NET Scaffolding feature enables you to automatically generate code
for displaying, updating, creating and deleting data.
This topic addresses the situation where you have a database and want to generate code for a web
application based on the fields of that database. This approach is called Database First
development. If you do not already have an existing database, you can instead use an approach
called Code First development which involves defining data classes and generating the database
from the class properties.
If this is the first data connection you have added, you will be prompted to choose a Data
source. Select Microsoft SQL Server. If you have added a data connection in the past, you
might not see this dialog window.
If you have a server that you prefer to use, you can specify the name of that server; otherwise,
use the local database that comes with Visual Studio by specifying (localdb)\v11.0 for the server
name. Name the database ContosoUniversity.
In the query window, you will add T-SQL commands to create 3 tables (Course, Student, and
Enrollment), and add some example data to those tables. Add the following code to the query
window:
CREATE TABLE [dbo].[Course] (
[CourseID] INT
IDENTITY (1, 1) NOT NULL,
[Title]
NVARCHAR (50) NULL,
[Credits] INT
NULL,
PRIMARY KEY CLUSTERED ([CourseID] ASC)
);
CREATE TABLE [dbo].[Student] (
[StudentID]
INT
IDENTITY (1, 1) NOT NULL,
[LastName]
NVARCHAR (50) NULL,
[FirstName]
NVARCHAR (50) NULL,
[EnrollmentDate] DATETIME
NULL,
PRIMARY KEY CLUSTERED ([StudentID] ASC)
);
CREATE TABLE [dbo].[Enrollment] (
[EnrollmentID] INT IDENTITY (1, 1) NOT NULL,
[Grade]
DECIMAL(3, 2) NULL,
[CourseID]
INT NOT NULL,
[StudentID]
INT NOT NULL,
PRIMARY KEY CLUSTERED ([EnrollmentID] ASC),
CONSTRAINT [FK_dbo.Enrollment_dbo.Course_CourseID] FOREIGN KEY
([CourseID])
REFERENCES [dbo].[Course] ([CourseID]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.Enrollment_dbo.Student_StudentID] FOREIGN KEY
([StudentID])
REFERENCES [dbo].[Student] ([StudentID]) ON DELETE CASCADE
);
INSERT INTO Course
(Title, Credits)
Values ('Economics', 3), ('Literature', 3), ('Chemistry', 4);
INSERT INTO Student
(LastName, FirstName, EnrollmentDate)
Execute the query (Ctrl + Shift + E). The tables now exist in the database.
After executing the query, you can close the query window without saving the file.
To see that the tables are populated with data, right-click a table, and select Show Table Data.
Your database is now set up and populated with data. In the next tutorial, you will create a web
application for the database.
Click OK.
In the New ASP.NET Project window, select the MVC template. Click OK to create the
application.
In the Add New Item window, select Data in the left pane and ADO.NET Entity Data Model
from the options in the center pane. Name the new model file ContosoModel.
Click Add.
In the Entity Data Model Wizard, select EF Designer from database.
10
Click Next.
Select the data connection you added earlier.
11
Click Next.
Select Tables to generate models for all three tables.
12
Click Finish.
If you receive a security warning, select OK to continue running the template.
The models are generated from the database tables, and a diagram is displayed that shows the
properties and relationships between the tables.
13
The Models folder now includes many new files related to the models that were generated from
the database.
The ContosoModel.Context.cs file contains a class that derives from the DbContext class, and
provides a property for each model class that corresponds to a database table. The Course.cs,
Enrollment.cs, and Student.cs files contain the model classes that represent the databases
tables. You will use both the context class and the model classes when working with scaffolding.
Before proceeding with this tutorial, build the project. In the next section, you will generate code
based on the data models, but that section will not work if the project has not been built.
14
3. Add scaffold
You are ready to generate code that will provide standard data operations for the model classes.
You add the code by adding a scaffold item. There are many options for the type of scaffolding
you can add; in this tutorial, the scaffold will include a controller and views that correspond to
the Student and Enrollment models you created in the previous section.
To maintain consistency in your project, you will add the new controller to the existing
Controllers folder. Right-click the Controllers folder, and select Add New Scaffolded Item.
Select the MVC 5 Controller with views, using Entity Framework option. This option will
generate the controller and views for updating, deleting, creating and displaying the data in your
model.
15
Select Student for the model class, and select the ContosoUniversityEntities for the context
class. Keep the controller name as StudentsController,
Click Add.
16
Perform the same steps again, but add a scaffold for the Enrollment class. When finished, you
should have an EnrollmentsController.cs file, and a folder under Views named Enrollments
with the Create, Delete, Details, Edit and Index views.
17
18
Click the Create New link and provide some values for a new student.
Click Create, and notice the new student is added to your list.
19
Select the Edit link, and change some of the values for a student.
Click Save, and notice the student record has been changed.
Finally, select the Delete link and confirm that you want to delete the record by clicking the
Delete button.
20
21
Furthermore, validation of the provided values is automatically applied based on the data type of
the field. Grade requires a number, so an error message is displayed if you try to provide an
incompatible value.
22
4. Add a column
If you update the structure of a table in your database, you need to ensure that your change is
propagated to the data model, views, and controller.
For this tutorial, you will add a new column to the Student table to record the middle name of the
student. To add this column, open a new query window and execute the following command.
ALTER TABLE [dbo].[Student]
ADD [MiddleName] NVARCHAR (50) NULL;
The new field has been added to the table. If you do not see it in the Server Explorer, click the
Refresh button in the pane.
The new column exists in the database table, but it does not currently exist in the data model
class. You must update the model to include your new column. In the Models folder, open the
ContosoModel.edmx file to display the model diagram. Notice that the Student model does not
contain the MiddleName property. Right-click anywhere on the design surface, and select
Update Model from Database.
23
In the Update Wizard, select the Refresh tab and the Student table.
24
Click Finish.
After the update process is finished, the database diagram includes the new MiddleName
property. Save the ContosoModel.edmx file. You must save this file for the new property to be
propagated to the Student.cs class. You have now updated the database and the model.
Build the solution.
Unfortunately, the views still do not contain the new property. To update the views you have two
options - you can either re-generate the views by once again adding scaffolding for the Student
class, or you can manually add the new property to your existing views. In this tutorial, you will
add the scaffolding again because you have not made any customized changes to the
automatically-generated views. You might consider manually adding the property when you
have made changes to the views and do not want to lose those changes.
25
In the next section, you will add code to customize the view for showing details about a student
record.
26
5. Customizing a View
Add enrolled courses to student details
The generated code provides a good starting point for your application but it does not necessarily
provide all of the functionality that you need in your application. You can customize the code to
meet the particular requirements of your application. Currently, your application does not display
the enrolled courses for the selected student. In this section, you will add the enrolled courses for
each student to the Details view for the student.
Open Students/Details.cshtml, and below the last </dl> tab, but before the closing </div> tag,
add the following code.
<table class="table">
<tr>
<th>
Course Title
</th>
<th>
Grade
</th>
<th>
Credits
</th>
</tr>
@foreach (var item in Model.Enrollments)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Course.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Grade)
</td>
<td>
@Html.DisplayFor(modelItem => item.Course.Credits)
</td>
</tr>
}
</table>
This code creates a table that displays a row for each record in the Enrollment table for the
selected student. Browse to the Students/Index view again and select Details for one of the
students. You will see the enrolled courses have been included in the view.
27
28
ContosoSite.Models
System;
System.Collections.Generic;
System.ComponentModel.DataAnnotations;
29
Browse to the page for editing enrollments, and attempt to provide a grade above 4.
For a full list of data validation annotations you can apply to properties and classes, see
System.ComponentModel.DataAnnotations.
30
31
32
33