Updating Related Data with the Entity Framework in an ASP.NET MVC Application (6 of 10)
by Tom Dykstra
The Contoso University sample web application demonstrates how to create ASP.NET MVC 4 applications using the Entity Framework 5 Code First and Visual Studio 2012. For information about the tutorial series, see the first tutorial in the series. You can start the tutorial series from the beginning or download a starter project for this chapter and start here.
[!NOTE]
If you run into a problem you can’t resolve, download the completed chapter and try to reproduce your problem. You can generally find the solution to the problem by comparing your code to the completed code. For some common errors and how to solve them, see Errors and Workarounds.
In the previous tutorial you displayed related data; in this tutorial you’ll update related data. For most relationships, this can be done by updating the appropriate foreign key fields. For many-to-many relationships, the Entity Framework doesn’t expose the join table directly, so you must explicitly add and remove entities to and from the appropriate navigation properties.
The following illustrations show the pages that you’ll work with.
Customize the Create and Edit Pages for Courses
When a new course entity is created, it must have a relationship to an existing department. To facilitate this, the scaffolded code includes controller methods and Create and Edit views that include a drop-down list for selecting the department. The drop-down list sets the Course.DepartmentID
foreign key property, and that’s all the Entity Framework needs in order to load the Department
navigation property with the appropriate Department
entity. You’ll use the scaffolded code, but change it slightly to add error handling and sort the drop-down list.
In CourseController.cs, delete the four Edit
and Create
methods and replace them with the following code:
[!code-csharpMain]
1: public ActionResult Create()
2: {
3: PopulateDepartmentsDropDownList();
4: return View();
5: }
6:
7: [HttpPost]
8: [ValidateAntiForgeryToken]
9: public ActionResult Create(
10: [Bind(Include = "CourseID,Title,Credits,DepartmentID")]
11: Course course)
12: {
13: try
14: {
15: if (ModelState.IsValid)
16: {
17: db.Courses.Add(course);
18: db.SaveChanges();
19: return RedirectToAction("Index");
20: }
21: }
22: catch (DataException /* dex */)
23: {
24: //Log the error (uncomment dex variable name after DataException and add a line here to write a log.)
25: ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
26: }
27: PopulateDepartmentsDropDownList(course.DepartmentID);
28: return View(course);
29: }
30:
31: public ActionResult Edit(int id)
32: {
33: Course course = db.Courses.Find(id);
34: PopulateDepartmentsDropDownList(course.DepartmentID);
35: return View(course);
36: }
37:
38: [HttpPost]
39: [ValidateAntiForgeryToken]
40: public ActionResult Edit(
41: [Bind(Include = "CourseID,Title,Credits,DepartmentID")]
42: Course course)
43: {
44: try
45: {
46: if (ModelState.IsValid)
47: {
48: db.Entry(course).State = EntityState.Modified;
49: db.SaveChanges();
50: return RedirectToAction("Index");
51: }
52: }
53: catch (DataException /* dex */)
54: {
55: //Log the error (uncomment dex variable name after DataException and add a line here to write a log.)
56: ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
57: }
58: PopulateDepartmentsDropDownList(course.DepartmentID);
59: return View(course);
60: }
61:
62: private void PopulateDepartmentsDropDownList(object selectedDepartment = null)
63: {
64: var departmentsQuery = from d in db.Departments
65: orderby d.Name
66: select d;
67: ViewBag.DepartmentID = new SelectList(departmentsQuery, "DepartmentID", "Name", selectedDepartment);
68: }
The PopulateDepartmentsDropDownList
method gets a list of all departments sorted by name, creates a SelectList
collection for a drop-down list, and passes the collection to the view in a ViewBag
property. The method accepts the optional selectedDepartment
parameter that allows the calling code to specify the item that will be selected when the drop-down list is rendered. The view will pass the name DepartmentID
to the DropDownList
helper, and the helper then knows to look in the ViewBag
object for a SelectList
named DepartmentID
.
The HttpGet
Create
method calls the PopulateDepartmentsDropDownList
method without setting the selected item, because for a new course the department is not established yet:
[!code-csharpMain]
1: public ActionResult Create()
2: {
3: PopulateDepartmentsDropDownList();
4: return View();
5: }
The HttpGet
Edit
method sets the selected item, based on the ID of the department that is already assigned to the course being edited:
[!code-csharpMain]
1: public ActionResult Edit(int id)
2: {
3: Course course = db.Courses.Find(id);
4: PopulateDepartmentsDropDownList(course.DepartmentID);
5: return View(course);
6: }
The HttpPost
methods for both Create
and Edit
also include code that sets the selected item when they redisplay the page after an error:
[!code-csharpMain]
1: catch (DataException /* dex */)
2: {
3: //Log the error (uncomment dex variable name after DataException and add a line here to write a log.)
4: ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
5: }
6: PopulateDepartmentsDropDownList(course.DepartmentID);
7: return View(course);
This code ensures that when the page is redisplayed to show the error message, whatever department was selected stays selected.
In Views.cshtml, add the highlighted code to create a new course number field before the Title field. As explained in an earlier tutorial, primary key fields aren’t scaffolded by default, but this primary key is meaningful, so you want the user to be able to enter the key value.
[!code-cshtmlMain]
1: @model ContosoUniversity.Models.Course
2:
3: @{
4: ViewBag.Title = "Create";
5: }
6:
7: <h2>Create</h2>
8:
9: @using (Html.BeginForm())
10: {
11: @Html.AntiForgeryToken()
12: @Html.ValidationSummary(true)
13:
14: <fieldset>
15: <legend>Course</legend>
16:
17: <div class="editor-label">
18: @Html.LabelFor(model => model.CourseID)
19: </div>
20: <div class="editor-field">
21: @Html.EditorFor(model => model.CourseID)
22: @Html.ValidationMessageFor(model => model.CourseID)
23: </div>
24:
25: <div class="editor-label">
26: @Html.LabelFor(model => model.Title)
27: </div>
28: <div class="editor-field">
29: @Html.EditorFor(model => model.Title)
30: @Html.ValidationMessageFor(model => model.Title)
31: </div>
32:
33: <div class="editor-label">
34: @Html.LabelFor(model => model.Credits)
35: </div>
36: <div class="editor-field">
37: @Html.EditorFor(model => model.Credits)
38: @Html.ValidationMessageFor(model => model.Credits)
39: </div>
40:
41: <div class="editor-label">
42: @Html.LabelFor(model => model.DepartmentID, "Department")
43: </div>
44: <div class="editor-field">
45: @Html.DropDownList("DepartmentID", String.Empty)
46: @Html.ValidationMessageFor(model => model.DepartmentID)
47: </div>
48:
49: <p>
50: <input type="submit" value="Create" />
51: </p>
52: </fieldset>
53: }
54:
55: <div>
56: @Html.ActionLink("Back to List", "Index")
57: </div>
58:
59: @section Scripts {
60: @Scripts.Render("~/bundles/jqueryval")
61: }
In Views.cshtml, Views.cshtml, and Views.cshtml, add a course number field before the Title field. Because it’s the primary key, it’s displayed, but it can’t be changed.
[!code-cshtmlMain]
1: <div class="editor-label">
2: @Html.LabelFor(model => model.CourseID)
3: </div>
4: <div class="editor-field">
5: @Html.DisplayFor(model => model.CourseID)
6: </div>
Run the Create page (display the Course Index page and click Create New) and enter data for a new course:
Click Create. The Course Index page is displayed with the new course added to the list. The department name in the Index page list comes from the navigation property, showing that the relationship was established correctly.
Run the Edit page (display the Course Index page and click Edit on a course).
Change data on the page and click Save. The Course Index page is displayed with the updated course data.
Adding an Edit Page for Instructors
When you edit an instructor record, you want to be able to update the instructor’s office assignment. The Instructor
entity has a one-to-zero-or-one relationship with the OfficeAssignment
entity, which means you must handle the following situations:
- If the user clears the office assignment and it originally had a value, you must remove and delete the
OfficeAssignment
entity. - If the user enters an office assignment value and it originally was empty, you must create a new
OfficeAssignment
entity. - If the user changes the value of an office assignment, you must change the value in an existing
OfficeAssignment
entity.
Open InstructorController.cs and look at the HttpGet
Edit
method:
[!code-csharpMain]
1: public ActionResult Edit(int id = 0)
2: {
3: Instructor instructor = db.Instructors.Find(id);
4: if (instructor == null)
5: {
6: return HttpNotFound();
7: }
8: ViewBag.InstructorID = new SelectList(db.OfficeAssignments, "InstructorID", "Location", instructor.InstructorID);
9: return View(instructor);
10: }
The scaffolded code here isn’t what you want. It’s setting up data for a drop-down list, but you what you need is a text box. Replace this method with the following code:
[!code-csharpMain]
1: public ActionResult Edit(int id)
2: {
3: Instructor instructor = db.Instructors
4: .Include(i => i.OfficeAssignment)
5: .Where(i => i.InstructorID == id)
6: .Single();
7: return View(instructor);
8: }
This code drops the ViewBag
statement and adds eager loading for the associated OfficeAssignment
entity. You can’t perform eager loading with the Find
method, so the Where
and Single
methods are used instead to select the instructor.
Replace the HttpPost
Edit
method with the following code. which handles office assignment updates:
[!code-csharpMain]
1: [HttpPost]
2: [ValidateAntiForgeryToken]
3: public ActionResult Edit(int id, FormCollection formCollection)
4: {
5: var instructorToUpdate = db.Instructors
6: .Include(i => i.OfficeAssignment)
7: .Where(i => i.InstructorID == id)
8: .Single();
9:
10: if (TryUpdateModel(instructorToUpdate, "",
11: new string[] { "LastName", "FirstMidName", "HireDate", "OfficeAssignment" }))
12: {
13: try
14: {
15: if (String.IsNullOrWhiteSpace(instructorToUpdate.OfficeAssignment.Location))
16: {
17: instructorToUpdate.OfficeAssignment = null;
18: }
19:
20: db.Entry(instructorToUpdate).State = EntityState.Modified;
21: db.SaveChanges();
22:
23: return RedirectToAction("Index");
24: }
25: catch (DataException /* dex */)
26: {
27: //Log the error (uncomment dex variable name after DataException and add a line here to write a log.
28: ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
29: }
30: }
31: ViewBag.InstructorID = new SelectList(db.OfficeAssignments, "InstructorID", "Location", id);
32: return View(instructorToUpdate);
33: }
The code does the following:
- Gets the current
Instructor
entity from the database using eager loading for theOfficeAssignment
navigation property. This is the same as what you did in theHttpGet
Edit
method. Updates the retrieved
[!code-csharpMain]Instructor
entity with values from the model binder. The TryUpdateModel overload used enables you to whitelist the properties you want to include. This prevents over-posting, as explained in the second tutorial.1: if (TryUpdateModel(instructorToUpdate, "",
2: new string[] { "LastName", "FirstMidName", "HireDate", "OfficeAssignment" }))
If the office location is blank, sets the
[!code-csharpMain]Instructor.OfficeAssignment
property to null so that the related row in theOfficeAssignment
table will be deleted.1: if (String.IsNullOrWhiteSpace(instructorToUpdate.OfficeAssignment.Location))
2: {
3: instructorToUpdate.OfficeAssignment = null;
4: }
Saves the changes to the database.
In Views.cshtml, after the div
elements for the Hire Date field, add a new field for editing the office location:
[!code-cshtmlMain]
1: <div class="editor-label">
2: @Html.LabelFor(model => model.OfficeAssignment.Location)
3: </div>
4: <div class="editor-field">
5: @Html.EditorFor(model => model.OfficeAssignment.Location)
6: @Html.ValidationMessageFor(model => model.OfficeAssignment.Location)
7: </div>
Run the page (select the Instructors tab and then click Edit on an instructor). Change the Office Location and click Save.
Adding Course Assignments to the Instructor Edit Page
Instructors may teach any number of courses. Now you’ll enhance the Instructor Edit page by adding the ability to change course assignments using a group of check boxes, as shown in the following screen shot:
The relationship between the Course
and Instructor
entities is many-to-many, which means you do not have direct access to the join table. Instead, you will add and remove entities to and from the Instructor.Courses
navigation property.
The UI that enables you to change which courses an instructor is assigned to is a group of check boxes. A check box for every course in the database is displayed, and the ones that the instructor is currently assigned to are selected. The user can select or clear check boxes to change course assignments. If the number of courses were much greater, you would probably want to use a different method of presenting the data in the view, but you’d use the same method of manipulating navigation properties in order to create or delete relationships.
To provide data to the view for the list of check boxes, you’ll use a view model class. Create AssignedCourseData.cs in the ViewModels folder and replace the existing code with the following code:
[!code-csharpMain]
1: namespace ContosoUniversity.ViewModels
2: {
3: public class AssignedCourseData
4: {
5: public int CourseID { get; set; }
6: public string Title { get; set; }
7: public bool Assigned { get; set; }
8: }
9: }
In InstructorController.cs, replace the HttpGet
Edit
method with the following code. The changes are highlighted.
[!code-csharpMain]
1: public ActionResult Edit(int id)
2: {
3: Instructor instructor = db.Instructors
4: .Include(i => i.OfficeAssignment)
5: .Include(i => i.Courses)
6: .Where(i => i.InstructorID == id)
7: .Single();
8: PopulateAssignedCourseData(instructor);
9: return View(instructor);
10: }
11:
12: private void PopulateAssignedCourseData(Instructor instructor)
13: {
14: var allCourses = db.Courses;
15: var instructorCourses = new HashSet<int>(instructor.Courses.Select(c => c.CourseID));
16: var viewModel = new List<AssignedCourseData>();
17: foreach (var course in allCourses)
18: {
19: viewModel.Add(new AssignedCourseData
20: {
21: CourseID = course.CourseID,
22: Title = course.Title,
23: Assigned = instructorCourses.Contains(course.CourseID)
24: });
25: }
26: ViewBag.Courses = viewModel;
27: }
The code adds eager loading for the Courses
navigation property and calls the new PopulateAssignedCourseData
method to provide information for the check box array using the AssignedCourseData
view model class.
The code in the PopulateAssignedCourseData
method reads through all Course
entities in order to load a list of courses using the view model class. For each course, the code checks whether the course exists in the instructor’s Courses
navigation property. To create efficient lookup when checking whether a course is assigned to the instructor, the courses assigned to the instructor are put into a HashSet collection. The Assigned
property is set to true
for courses the instructor is assigned. The view will use this property to determine which check boxes must be displayed as selected. Finally, the list is passed to the view in a ViewBag
property.
Next, add the code that’s executed when the user clicks Save. Replace the HttpPost
Edit
method with the following code, which calls a new method that updates the Courses
navigation property of the Instructor
entity. The changes are highlighted.
[!code-csharpMain]
1: [HttpPost]
2: [ValidateAntiForgeryToken]
3: public ActionResult Edit(int id, FormCollection formCollection, string[] selectedCourses)
4: {
5: var instructorToUpdate = db.Instructors
6: .Include(i => i.OfficeAssignment)
7: .Include(i => i.Courses)
8: .Where(i => i.InstructorID == id)
9: .Single();
10: if (TryUpdateModel(instructorToUpdate, "",
11: new string[] { "LastName", "FirstMidName", "HireDate", "OfficeAssignment" }))
12: {
13: try
14: {
15: if (String.IsNullOrWhiteSpace(instructorToUpdate.OfficeAssignment.Location))
16: {
17: instructorToUpdate.OfficeAssignment = null;
18: }
19:
20: UpdateInstructorCourses(selectedCourses, instructorToUpdate);
21:
22: db.Entry(instructorToUpdate).State = EntityState.Modified;
23: db.SaveChanges();
24:
25: return RedirectToAction("Index");
26: }
27: catch (DataException /* dex */)
28: {
29: //Log the error (uncomment dex variable name after DataException and add a line here to write a log.
30: ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
31: }
32: }
33: PopulateAssignedCourseData(instructorToUpdate);
34: return View(instructorToUpdate);
35: }
36:
37: private void UpdateInstructorCourses(string[] selectedCourses, Instructor instructorToUpdate)
38: {
39: if (selectedCourses == null)
40: {
41: instructorToUpdate.Courses = new List<Course>();
42: return;
43: }
44:
45: var selectedCoursesHS = new HashSet<string>(selectedCourses);
46: var instructorCourses = new HashSet<int>
47: (instructorToUpdate.Courses.Select(c => c.CourseID));
48: foreach (var course in db.Courses)
49: {
50: if (selectedCoursesHS.Contains(course.CourseID.ToString()))
51: {
52: if (!instructorCourses.Contains(course.CourseID))
53: {
54: instructorToUpdate.Courses.Add(course);
55: }
56: }
57: else
58: {
59: if (instructorCourses.Contains(course.CourseID))
60: {
61: instructorToUpdate.Courses.Remove(course);
62: }
63: }
64: }
65: }
Since the view doesn’t have a collection of Course
entities, the model binder can’t automatically update the Courses
navigation property. Instead of using the model binder to update the Courses navigation property, you’ll do that in the new UpdateInstructorCourses
method. Therefore you need to exclude the Courses
property from model binding. This doesn’t require any change to the code that calls TryUpdateModel because you’re using the whitelisting overload and Courses
isn’t in the include list.
If no check boxes were selected, the code in UpdateInstructorCourses
initializes the Courses
navigation property with an empty collection:
[!code-csharpMain]
1: if (selectedCourses == null)
2: {
3: instructorToUpdate.Courses = new List<Course>();
4: return;
5: }
The code then loops through all courses in the database and checks each course against the ones currently assigned to the instructor versus the ones that were selected in the view. To facilitate efficient lookups, the latter two collections are stored in HashSet
objects.
If the check box for a course was selected but the course isn’t in the Instructor.Courses
navigation property, the course is added to the collection in the navigation property.
[!code-csharpMain]
1: if (selectedCoursesHS.Contains(course.CourseID.ToString()))
2: {
3: if (!instructorCourses.Contains(course.CourseID))
4: {
5: instructorToUpdate.Courses.Add(course);
6: }
7: }
If the check box for a course wasn’t selected, but the course is in the Instructor.Courses
navigation property, the course is removed from the navigation property.
[!code-csharpMain]
1: else
2: {
3: if (instructorCourses.Contains(course.CourseID))
4: {
5: instructorToUpdate.Courses.Remove(course);
6: }
7: }
In Views.cshtml, add a Courses field with an array of check boxes by adding the following highlighted code immediately after the div
elements for the OfficeAssignment
field:
[!code-cshtmlMain]
1: @model ContosoUniversity.Models.Instructor
2:
3: @{
4: ViewBag.Title = "Edit";
5: }
6:
7: <h2>Edit</h2>
8:
9: @using (Html.BeginForm())
10: {
11: @Html.AntiForgeryToken()
12: @Html.ValidationSummary(true)
13:
14: <fieldset>
15: <legend>Instructor</legend>
16:
17: @Html.HiddenFor(model => model.InstructorID)
18:
19: <div class="editor-label">
20: @Html.LabelFor(model => model.LastName)
21: </div>
22: <div class="editor-field">
23: @Html.EditorFor(model => model.LastName)
24: @Html.ValidationMessageFor(model => model.LastName)
25: </div>
26:
27: <div class="editor-label">
28: @Html.LabelFor(model => model.FirstMidName)
29: </div>
30: <div class="editor-field">
31: @Html.EditorFor(model => model.FirstMidName)
32: @Html.ValidationMessageFor(model => model.FirstMidName)
33: </div>
34:
35: <div class="editor-label">
36: @Html.LabelFor(model => model.HireDate)
37: </div>
38: <div class="editor-field">
39: @Html.EditorFor(model => model.HireDate)
40: @Html.ValidationMessageFor(model => model.HireDate)
41: </div>
42:
43: <div class="editor-label">
44: @Html.LabelFor(model => model.OfficeAssignment.Location)
45: </div>
46: <div class="editor-field">
47: @Html.EditorFor(model => model.OfficeAssignment.Location)
48: @Html.ValidationMessageFor(model => model.OfficeAssignment.Location)
49: </div>
50:
51: <div class="editor-field">
52: <table>
53: <tr>
54: @{
55: int cnt = 0;
56: List<ContosoUniversity.ViewModels.AssignedCourseData> courses = ViewBag.Courses;
57:
58: foreach (var course in courses) {
59: if (cnt++ % 3 == 0) {
60: @: </tr> <tr>
61: }
62: @: <td>
63: <input type="checkbox"
64: name="selectedCourses"
65: value="@course.CourseID"
66: @(Html.Raw(course.Assigned ? "checked=\"checked\"" : "")) />
67: @course.CourseID @: @course.Title
68: @:</td>
69: }
70: @: </tr>
71: }
72: </table>
73: </div>
74: <p>
75: <input type="submit" value="Save" />
76: </p>
77: </fieldset>
78: }
79:
80: <div>
81: @Html.ActionLink("Back to List", "Index")
82: </div>
83:
84: @section Scripts {
85: @Scripts.Render("~/bundles/jqueryval")
86: }
This code creates an HTML table that has three columns. In each column is a check box followed by a caption that consists of the course number and title. The check boxes all have the same name (“selectedCourses”), which informs the model binder that they are to be treated as a group. The value
attribute of each check box is set to the value of CourseID.
When the page is posted, the model binder passes an array to the controller that consists of the CourseID
values for only the check boxes which are selected.
When the check boxes are initially rendered, those that are for courses assigned to the instructor have checked
attributes, which selects them (displays them checked).
After changing course assignments, you’ll want to be able to verify the changes when the site returns to the Index
page. Therefore, you need to add a column to the table in that page. In this case you don’t need to use the ViewBag
object, because the information you want to display is already in the Courses
navigation property of the Instructor
entity that you’re passing to the page as the model.
In Views.cshtml, add a Courses heading immediately following the Office heading, as shown in the following example:
[!code-htmlMain]
1: <tr>
2: <th></th>
3: <th>Last Name</th>
4: <th>First Name</th>
5: <th>Hire Date</th>
6: <th>Office</th>
7: <th>Courses</th>
8: </tr>
Then add a new detail cell immediately following the office location detail cell:
[!code-cshtmlMain]
1: @model ContosoUniversity.ViewModels.InstructorIndexData
2:
3: @{
4: ViewBag.Title = "Instructors";
5: }
6:
7: <h2>Instructors</h2>
8:
9: <p>
10: @Html.ActionLink("Create New", "Create")
11: </p>
12: <table>
13: <tr>
14: <th></th>
15: <th>Last Name</th>
16: <th>First Name</th>
17: <th>Hire Date</th>
18: <th>Office</th>
19: <th>Courses</th>
20: </tr>
21: @foreach (var item in Model.Instructors)
22: {
23: string selectedRow = "";
24: if (item.InstructorID == ViewBag.InstructorID)
25: {
26: selectedRow = "selectedrow";
27: }
28: <tr class="@selectedRow" valign="top">
29: <td>
30: @Html.ActionLink("Select", "Index", new { id = item.InstructorID }) |
31: @Html.ActionLink("Edit", "Edit", new { id = item.InstructorID }) |
32: @Html.ActionLink("Details", "Details", new { id = item.InstructorID }) |
33: @Html.ActionLink("Delete", "Delete", new { id = item.InstructorID })
34: </td>
35: <td>
36: @item.LastName
37: </td>
38: <td>
39: @item.FirstMidName
40: </td>
41: <td>
42: @String.Format("{0:d}", item.HireDate)
43: </td>
44: <td>
45: @if (item.OfficeAssignment != null)
46: {
47: @item.OfficeAssignment.Location
48: }
49: </td>
50: <td>
51: @{
52: foreach (var course in item.Courses)
53: {
54: @course.CourseID @: @course.Title <br />
55: }
56: }
57: </td>
58: </tr>
59: }
60: </table>
61:
62: @if (Model.Courses != null)
63: {
64: <h3>Courses Taught by Selected Instructor</h3>
65: <table>
66: <tr>
67: <th></th>
68: <th>ID</th>
69: <th>Title</th>
70: <th>Department</th>
71: </tr>
72:
73: @foreach (var item in Model.Courses)
74: {
75: string selectedRow = "";
76: if (item.CourseID == ViewBag.CourseID)
77: {
78: selectedRow = "selectedrow";
79: }
80:
81: <tr class="@selectedRow">
82:
83: <td>
84: @Html.ActionLink("Select", "Index", new { courseID = item.CourseID })
85: </td>
86: <td>
87: @item.CourseID
88: </td>
89: <td>
90: @item.Title
91: </td>
92: <td>
93: @item.Department.Name
94: </td>
95: </tr>
96: }
97:
98: </table>
99: }
100: @if (Model.Enrollments != null)
101: {
102: <h3>Students Enrolled in Selected Course</h3>
103: <table>
104: <tr>
105: <th>Name</th>
106: <th>Grade</th>
107: </tr>
108: @foreach (var item in Model.Enrollments)
109: {
110: <tr>
111: <td>
112: @item.Student.FullName
113: </td>
114: <td>
115: @Html.DisplayFor(modelItem => item.Grade)
116: </td>
117: </tr>
118: }
119: </table>
120: }
Run the Instructor Index page to see the courses assigned to each instructor:
Click Edit on an instructor to see the Edit page.
Change some course assignments and click Save. The changes you make are reflected on the Index page.
Note: The approach taken to edit instructor course data works well when there is a limited number of courses. For collections that are much larger, a different UI and a different updating method would be required.
Update the Delete Method
Change the code in the HttpPost Delete method so the office assignment record (if any) is deleted when the instructor is deleted:
[!code-csharpMain]
1: [HttpPost, ActionName("Delete")]
2: [ValidateAntiForgeryToken]
3: public ActionResult DeleteConfirmed(int id)
4: {
5: Instructor instructor = db.Instructors
6: .Include(i => i.OfficeAssignment)
7: .Where(i => i.InstructorID == id)
8: .Single();
9:
10: instructor.OfficeAssignment = null;
11: db.Instructors.Remove(instructor);
12: db.SaveChanges();
13: return RedirectToAction("Index");
14: }
If you try to delete an instructor who is assigned to a department as administrator, you’ll get a referential integrity error. See the current version of this tutorial for additional code that will automatically remove the instructor from any department where the instructor is assigned as an administrator.
Summary
You have now completed this introduction to working with related data. So far in these tutorials you’ve done a full range of CRUD operations, but you haven’t dealt with concurrency issues. The next tutorial will introduce the topic of concurrency, explain options for handling it, and add concurrency handling to the CRUD code you’ve already written for one entity type.
Links to other Entity Framework resources, can be found at the end of the last tutorial in this series.
|