+ All Categories
Home > Documents > Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ......

Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ......

Date post: 02-Apr-2018
Category:
Upload: lamque
View: 220 times
Download: 3 times
Share this document with a friend
44
12/5/2012 http://torahlawform.com/Documents/ 1 of 44 Contoso University MVC 3 Sample Project A Visual Studio project which shows how to use the Entity Framework in an ASP.NET MVC web application project, using the Code First development approach. The code illustrates the following topics: Creating a data model using data annotations attributes, and fluent API for database mapping. Performing basic CRUD operations. Filtering, ordering, and grouping data. Working with related data. Handling concurrency. Implementing table-per-hierarchy inheritance. Implementing the repository and unit of work patterns. Performing raw SQL queries. Performing no-tracking queries. Working with proxy classes. Disabling automatic detection of changes. Disabling validation when saving changes. Getting Started To build and run this sample, you must have Visual Studio 2010 SP1 and MVC 3 with the MVC 3 Tools Update installed. Source Code Overview The ContosoUniversity folder includes the following folders and files App_Data folder - Holds the SQL Server Compact database file. Content - Holds CSS files. Controllers - Holds controller classes. DAL folder - The data access layer. Holds the context, initializer , repository , and unit of work classes . Models folder - Holds model classes. Properties or MyProject folder - Project properties. Scripts folder - Script files. ViewModels folder - Holds view model classes. Views folder - Holds view classes. Visual Studio project file (.csproj or .vbproj). packages.config - Specifies NuGet packages included in the project. Global.asax file - Includes database initializer code. Web.config file - Includes the connection string to the database. Table-per-hierarchy inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy
Transcript
Page 1: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 1 of 44

Contoso University MVC 3 Sample Project

A Visual Studio project which shows how to use the Entity Framework in an ASP.NET MVC web application project, using the Code First development approach. The code illustrates the following topics:

Creating a data model using data annotations attributes, and fluent API for database mapping.

Performing basic CRUD operations. Filtering, ordering, and grouping data. Working with related data. Handling concurrency.

Implementing table-per-hierarchy inheritance. Implementing the repository and unit of work patterns. Performing raw SQL queries. Performing no-tracking queries. Working with proxy classes. Disabling automatic detection of changes. Disabling validation when saving changes.

Getting Started

To build and run this sample, you must have Visual Studio 2010 SP1 and MVC 3 with the MVC 3 Tools Update installed.

Source Code Overview

The ContosoUniversity folder includes the following folders and files

App_Data folder - Holds the SQL Server Compact database

file. Content - Holds CSS files. Controllers - Holds controller classes. DAL folder - The data access layer. Holds the context,

initializer, repository, and unit of work classes. Models folder - Holds model classes. Properties or MyProject folder - Project properties.

Scripts folder - Script files. ViewModels folder - Holds view model classes. Views folder - Holds view classes. Visual Studio project file (.csproj or .vbproj). packages.config - Specifies NuGet packages included in the

project. Global.asax file - Includes database initializer code.

Web.config file - Includes the connection string to the database.

Table-per-hierarchy inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy

Page 2: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 2 of 44

Table of Contents

Getting Started ................................................................................................................................................................. 1

Source Code Overview .................................................................................................................................................... 1

DAL ................................................................................................................................................................................ 3

Models ............................................................................................................................................................................. 3

Course ......................................................................................................................................................................... 3

Department .................................................................................................................................................................. 3

Enrollment ................................................................................................................................................................... 4

OfficeAssignment ........................................................................................................................................................ 4

Person .......................................................................................................................................................................... 5

Student ......................................................................................................................................................................... 5

Instructor ..................................................................................................................................................................... 5

Course ............................................................................................................................................................................. 6

CourseController .......................................................................................................................................................... 6

View: Course Index...................................................................................................................................................... 8

Department .....................................................................................................................................................................12

DepartmentController..................................................................................................................................................12

Views..........................................................................................................................................................................15

Delete .....................................................................................................................................................................15

Instructor ........................................................................................................................................................................16

Screen - Index .............................................................................................................................................................16

InstructorController – Index Code ...............................................................................................................................17

InstructorController – Other Non Edit Code ................................................................................................................18

ViewModels\InstructorIndexData ................................................................................................................................19

View\Index .................................................................................................................................................................19

Screen - Edit ...............................................................................................................................................................21

InstructorController – Edit Code..................................................................................................................................22

ViewModels\AssignedCourseData ..............................................................................................................................25

View\Edit ....................................................................................................................................................................25

Student ...........................................................................................................................................................................28

SchoolContext {code related to Student} .....................................................................................................................28

IStudentRepository and StudentRepository ..................................................................................................................28

StudentController ........................................................................................................................................................29

StudentController – Dependency Injection Related Code ........................................................................................29

Screen - Index.........................................................................................................................................................30

StudentController – Index Code ..............................................................................................................................31

View\Index .................................................................................................................................................................32

Home ..............................................................................................................................................................................34

HomeController ..........................................................................................................................................................34

ViewModels\EnrollmentDateGroup ............................................................................................................................34

Views\Home\About.....................................................................................................................................................35

Screen - About ............................................................................................................................................................35

SchoolInitializer ..........................................................................................................................................................36

My Notes on the Repository ............................................................................................................................................38

Page 3: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 3 of 44

GenericRepository - Summary ....................................................................................................................................38

CourseRepository ........................................................................................................................................................39

IStudentRepository ......................................................................................................................................................39

StudentRepository - Summary .....................................................................................................................................39

StudentController ...................................................................................................................................................39

SchoolContext .............................................................................................................................................................40

UnitOfWork ................................................................................................................................................................40

GenericRepository - Detail ..........................................................................................................................................42

DbSet(Of TEntity).......................................................................................................................................................44

Set(Of TEntity As Class)() ..........................................................................................................................................44

DAL

See My Notes on the Repository.

Models

Course Imports System.Collections.Generic Imports System.ComponentModel.DataAnnotations Public Class Course <DatabaseGenerated(DatabaseGeneratedOption.None)> _ <Display(Name:="Number")> _ Public Property CourseID() As Integer <Required(ErrorMessage:="Title is required.")> _ <MaxLength(50)> _ Public Property Title() As String <Required(ErrorMessage:="Number of credits is required.")> _ <Range(0, 5, ErrorMessage:="Number of credits must be between 0 and 5.")> _ Public Property Credits() As Integer <Display(Name:="Department")> _ Public Property DepartmentID() As Integer Public Overridable Property Department() As Department Public Overridable Property Enrollments() As ICollection(Of Enrollment) Public Overridable Property Instructors() As ICollection(Of Instructor) End Class

Department Imports System.Collections.Generic Imports System.ComponentModel.DataAnnotations Public Class Department Public Property DepartmentID() As Integer <Required(ErrorMessage:="Department name is required.")> _ <MaxLength(50)> _ Public Property Name() As String

Page 4: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 4 of 44

<DisplayFormat(DataFormatString:="{0:c}")> _ <Required(ErrorMessage:="Budget is required.")> _ <Column(TypeName:="money")> _ Public Property Budget() As System.Nullable(Of Decimal) <DisplayFormat(DataFormatString:="{0:d}", ApplyFormatInEditMode:=True)> _ <Required(ErrorMessage:="Start date is required.")> _ Public Property StartDate() As DateTime <Display(Name:="Administrator")> _ Public Property PersonID() As System.Nullable(Of Integer) <Timestamp()> _ Public Property Timestamp() As [Byte]() Public Overridable Property Administrator() As Instructor Public Overridable Property Courses() As ICollection(Of Course) End Class

Enrollment Imports System.Collections.Generic Imports System.ComponentModel.DataAnnotations Public Class Enrollment Public Property EnrollmentID() As Integer Public Property CourseID() As Integer Public Property PersonID() As Integer <DisplayFormat(DataFormatString:="{0:#.#}", ApplyFormatInEditMode:=True, NullDisplayText:="No grade")> _ Public Property Grade() As System.Nullable(Of Decimal) Public Overridable Property Course() As Course Public Overridable Property Student() As Student End Class

OfficeAssignment Imports System.Collections.Generic Imports System.ComponentModel.DataAnnotations Public Class OfficeAssignment <Key()> _ Public Property PersonID() As Integer <MaxLength(50)> _ <Display(Name:="Office Location")> _ Public Property Location() As String Public Overridable Property Instructor() As Instructor End Class

Page 5: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 5 of 44

Person Imports System.Collections.Generic Imports System.ComponentModel.DataAnnotations Public MustInherit Class Person <Key()> _ Public Property PersonID() As Integer <Required(ErrorMessage:="Last name is required.")> _ <Display(Name:="Last Name")> _ <MaxLength(50)> _ Public Property LastName() As String <Required(ErrorMessage:="First name is required.")> _ <Column("FirstName")> _ <Display(Name:="First Name")> _ <MaxLength(50)> _ Public Property FirstMidName() As String Public ReadOnly Property FullName() As String Get Return LastName & ", " & FirstMidName End Get End Property End Class

Student Imports System.Collections.Generic Imports System.ComponentModel.DataAnnotations Public Class Student Inherits Person <Required(ErrorMessage:="Enrollment date is required.")> _ <DisplayFormat(DataFormatString:="{0:d}", ApplyFormatInEditMode:=True)> _ <Display(Name:="Enrollment Date")> _ Public Property EnrollmentDate() As System.Nullable(Of DateTime) Public Overridable Property Enrollments() As ICollection(Of Enrollment) End Class

Instructor Imports System.Collections.Generic Imports System.ComponentModel.DataAnnotations Public Class Instructor Inherits Person <DisplayFormat(DataFormatString:="{0:d}", ApplyFormatInEditMode:=True)> _ <Required(ErrorMessage:="Hire date is required.")> _ <Display(Name:="Hire Date")> _ Public Property HireDate() As System.Nullable(Of DateTime) Public Overridable Property Courses() As ICollection(Of Course) Public Overridable Property OfficeAssignment() As OfficeAssignment End Class

Page 6: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 6 of 44

Course

CourseController Imports System.Data.Entity Imports ContosoUniversity Namespace ContosoUniversity Public Class CourseController Inherits System.Web.Mvc.Controller Private unitOfWork As New UnitOfWork() ' GET: /Course/ Public Function Index(SelectedDepartment? As Integer) As ActionResult Dim departments = unitOfWork.DepartmentRepository.Get(orderBy:=Function(q) q.OrderBy(Function(d) d.Name)) ViewBag.SelectedDepartment = New SelectList(departments, "DepartmentID", "Name", SelectedDepartment) Dim departmentID As Integer = SelectedDepartment.GetValueOrDefault() Return View(unitOfWork.CourseRepository.Get( filter:=Function(d) Not SelectedDepartment.HasValue OrElse d.DepartmentID = departmentID, orderBy:=Function(q) q.OrderBy(Function(d) d.CourseID), includeProperties:="Department")) End Function ' ' GET: /Course/Details/5 Function Details(id As Integer) As ViewResult Dim query = "SELECT * FROM Course WHERE CourseID = @p0" Return View(unitOfWork.CourseRepository.GetWithRawSql(query, id).Single()) End Function ' ' GET: /Course/Create Function Create() As ViewResult PopulateDepartmentsDropDownList() Return View() End Function ' ' POST: /Course/Create <HttpPost()> Function Create(course As Course) As ActionResult Try If ModelState.IsValid Then unitOfWork.CourseRepository.Insert(course) unitOfWork.Save() Return RedirectToAction("Index") End If Catch ex As DataException 'Log the error ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.") End Try PopulateDepartmentsDropDownList(course.DepartmentID) Return View(course) End Function

Page 7: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 7 of 44

' ' GET: /Course/Edit/5 Function Edit(id As Integer) As ViewResult Dim course As Course = unitOfWork.CourseRepository.GetByID(id) PopulateDepartmentsDropDownList(course.DepartmentID) Return View(course) End Function ' ' POST: /Course/Edit/5 <HttpPost()> Function Edit(course As Course) As ActionResult Try If ModelState.IsValid Then unitOfWork.CourseRepository.Update(course) unitOfWork.Save() Return RedirectToAction("Index") End If Catch ex As DataException 'Log the error ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.") End Try PopulateDepartmentsDropDownList(course.DepartmentID) Return View(course) End Function 'Called by the HTTP Get of Create and Edit Private Sub PopulateDepartmentsDropDownList(Optional selectedDepartment As Object = Nothing) Dim departmentsQuery = unitOfWork.DepartmentRepository.Get (orderBy:=Function(q) q.OrderBy(Function(d) d.Name)) ViewBag.DepartmentID = New SelectList(departmentsQuery, "DepartmentID", "Name", selectedDepartment) End Sub ' ' GET: /Course/Delete/5 Function Delete(id As Integer) As ViewResult Dim course As Course = unitOfWork.CourseRepository.GetByID(id) Return View(course) End Function ' ' POST: /Course/Delete/5 <HttpPost()> <ActionName("Delete")> Function DeleteConfirmed(id As Integer) As RedirectToRouteResult unitOfWork.CourseRepository.Delete(id) unitOfWork.Save() Return RedirectToAction("Index") End Function Protected Overrides Sub Dispose(disposing As Boolean) unitOfWork.Dispose() MyBase.Dispose(disposing) End Sub End Class End Namespace

Page 8: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 8 of 44

View: Course Index

@ModelType IEnumerable(Of ContosoUniversity.Course) @Code ViewData("Title") = "Courses" End Code <h2>Courses</h2> <p> @Html.ActionLink("Create New", "Create") </p> @Using (Html.BeginForm()) @<p>Select Department: @Html.DropDownList("SelectedDepartment", "All") &nbsp; <input type="submit" value="Filter" /></p> End Using <table> <tr> <th></th> <th>Number</th> <th>Title</th> <th>Credits</th> <th>Department</th> </tr> @For Each item In Model Dim currentItem = item @<tr> <td> @Html.ActionLink("Edit", "Edit", New With {.id = currentItem.CourseID}) | @Html.ActionLink("Details", "Details", New With {.id = currentItem.CourseID}) | @Html.ActionLink("Delete", "Delete", New With {.id = currentItem.CourseID}) </td> <td>@Html.DisplayFor(Function(modelItem) currentItem.CourseID)</td> <td>@Html.DisplayFor(Function(modelItem) currentItem.Title)</td> <td>@Html.DisplayFor(Function(modelItem) currentItem.Credits)</td> <td>@Html.DisplayFor(Function(modelItem) currentItem.Department.Name) </td> </tr> Next </table>

Page 9: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 9 of 44

@ModelType ContosoUniversity.Course @Code ViewData("Title") = "Create" End Code <h2>Create</h2> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> @Using Html.BeginForm() @Html.ValidationSummary(True) @<fieldset> <legend>Course</legend> <div class="editor-label"> @Html.LabelFor(Function(model) model.CourseID) </div> <div class="editor-field"> @Html.EditorFor(Function(model) model.CourseID) @Html.ValidationMessageFor(Function(model) model.CourseID) </div> <div class="editor-label"> @Html.LabelFor(Function(model) model.Title) </div> <div class="editor-field"> @Html.EditorFor(Function(model) model.Title) @Html.ValidationMessageFor(Function(model) model.Title) </div> <div class="editor-label"> @Html.LabelFor(Function(model) model.Credits) </div> <div class="editor-field"> @Html.EditorFor(Function(model) model.Credits) @Html.ValidationMessageFor(Function(model) model.Credits) </div> <div class="editor-label"> @Html.LabelFor(Function(model) model.DepartmentID, "Department") </div> <div class="editor-field"> @Html.DropDownList("DepartmentID", String.Empty) @Html.ValidationMessageFor(Function(model) model.DepartmentID) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> End Using <div> @Html.ActionLink("Back to List", "Index") </div>

Page 10: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 10 of 44

@ModelType ContosoUniversity.Course @Code ViewData("Title") = "Edit" End Code <h2>Edit</h2> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> @Using Html.BeginForm() @Html.ValidationSummary(True) @<fieldset> <legend>Course</legend> @Html.HiddenFor(Function(model) model.CourseID) <div class="display-label"> @Html.LabelFor(Function(model) model.CourseID) </div> <div class="display-field"> @Html.DisplayFor(Function(model) model.CourseID) </div> <div class="editor-label"> @Html.LabelFor(Function(model) model.Title) </div> <div class="editor-field"> @Html.EditorFor(Function(model) model.Title) @Html.ValidationMessageFor(Function(model) model.Title) </div> <div class="editor-label"> @Html.LabelFor(Function(model) model.Credits) </div> <div class="editor-field"> @Html.EditorFor(Function(model) model.Credits) @Html.ValidationMessageFor(Function(model) model.Credits) </div> <div class="editor-label"> @Html.LabelFor(Function(model) model.DepartmentID, "Department") </div> <div class="editor-field"> @Html.DropDownList("DepartmentID", String.Empty) @Html.ValidationMessageFor(Function(model) model.DepartmentID) </div> <p> <input type="submit" value="Save" /> </p> </fieldset> End Using <div> @Html.ActionLink("Back to List", "Index") </div>

Page 11: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 11 of 44

Details view not shown @ModelType ContosoUniversity.Course @Code ViewData("Title") = "Delete" End Code <h2>Delete</h2> <h3>Are you sure you want to delete this?</h3> <fieldset> <legend>Course</legend> <div class="display-label"> @Html.LabelFor(Function(model) model.CourseID) </div> <div class="display-field"> @Html.DisplayFor(Function(model) model.CourseID) </div> <div class="display-label">Title</div> <div class="display-field"> @Html.DisplayFor(Function(model) model.Title) </div> <div class="display-label">Credits</div> <div class="display-field"> @Html.DisplayFor(Function(model) model.Credits) </div> <div class="display-label">Department</div> <div class="display-field"> @Html.DisplayFor(Function(model) model.Department.Name) </div> </fieldset> @Using Html.BeginForm() @<p> <input type="submit" value="Delete" /> | @Html.ActionLink("Back to List", "Index") </p> End Using

Page 12: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 12 of 44

Department

DepartmentController

Imports System.Data.Entity Imports ContosoUniversity Imports System.Data.Entity.Infrastructure Namespace ContosoUniversity Public Class DepartmentController Inherits System.Web.Mvc.Controller Private db As SchoolContext = New SchoolContext ' ' GET: /Department/ Function Index() As ViewResult ' Public Overridable Property Administrator() As Instructor Dim departments = db.Departments.Include(Function(d) d.Administrator) Return View(departments.ToList()) End Function ' ' GET: /Department/Details/5 Function Details(id As Integer) As ViewResult Dim department As Department = db.Departments.Find(id) Return View(department) End Function ' ' GET: /Department/Create Function Create() As ViewResult ViewBag.PersonID = New SelectList(db.Instructors, "PersonID", "FullName") Return View() End Function '

Page 13: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 13 of 44

' POST: /Department/Create <HttpPost()> Function Create(department As Department) As ActionResult If ModelState.IsValid Then db.Departments.Add(department) db.SaveChanges() Return RedirectToAction("Index") End If ViewBag.PersonID = New SelectList(db.Instructors, "PersonID", "FullName", department.PersonID) Return View(department) End Function ' ' GET: /Department/Edit/5 Function Edit(id As Integer) As ViewResult Dim department As Department = db.Departments.Find(id) ViewBag.PersonID = New SelectList(db.Instructors, "PersonID", "FullName", department.PersonID) Return View(department) End Function ' ' POST: /Department/Edit/5 <HttpPost()> _ Public Function Edit(department As Department) As ActionResult Try If ModelState.IsValid Then ValidateOneAdministratorAssignmentPerInstructor(department) End If If ModelState.IsValid Then db.Entry(department).State = EntityState.Modified db.SaveChanges() Return RedirectToAction("Index") End If Catch ex As DbUpdateConcurrencyException Dim entry = ex.Entries.First() Dim databaseValues = DirectCast(entry.GetDatabaseValues().ToObject(), Department) Dim clientValues = DirectCast(entry.Entity, Department) If databaseValues.Name <> clientValues.Name Then ModelState.AddModelError("Name", "Current value: " & Convert.ToString(databaseValues.Name)) End If If databaseValues.Budget <> clientValues.Budget Then ModelState.AddModelError("Budget", "Current value: " & [String].Format("{0:c}", databaseValues.Budget)) End If If databaseValues.StartDate <> clientValues.StartDate Then ModelState.AddModelError("StartDate", "Current value: " & [String].Format("{0:d}", databaseValues.StartDate)) End If If databaseValues.PersonID <> clientValues.PersonID Then ModelState.AddModelError("PersonID", "Current value: " + db.Instructors.Find(databaseValues.PersonID).FullName) End If ModelState.AddModelError(String.Empty, "The record you attempted to edit " & "was modified by another user after you got the original value. The " & "edit operation was canceled and the current values in the database " & "have been displayed. If you still want to edit this record, click " & "the Save button again. Otherwise click the Back to List hyperlink.") department.Timestamp = databaseValues.Timestamp

Page 14: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 14 of 44

Catch ex As DataException 'Log the error ModelState.AddModelError(String.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.") End Try ViewBag.PersonID = New SelectList(db.Instructors, "PersonID", "FullName", department.PersonID) Return View(department) End Function ' ' GET: /Department/Delete/5 Public Function Delete(id As Integer, concurrencyError As System.Nullable(Of Boolean)) As ActionResult If concurrencyError.GetValueOrDefault() Then ViewBag.ConcurrencyErrorMessage = "The record you attempted to delete " & "was modified by another user after you got the original values. " & "The delete operation was canceled and the current values in the " & "database have been displayed. If you still want to delete this " & "record, click the Delete button again. Otherwise " & "click the Back to List hyperlink." End If Dim department As Department = db.Departments.Find(id) Return View(department) End Function ' ' POST: /Department/Delete/5 <HttpPost(), ActionName("Delete")> _ Public Function DeleteConfirmed(department As Department) As ActionResult Try db.Entry(department).State = EntityState.Deleted db.SaveChanges() Return RedirectToAction("Index") Catch generatedExceptionName As DbUpdateConcurrencyException Return RedirectToAction("Delete", New System.Web.Routing.RouteValueDictionary() From {{"concurrencyError", True}}) Catch ex As DataException 'Log the error ModelState.AddModelError(String.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.") Return View(department) End Try End Function Private Sub ValidateOneAdministratorAssignmentPerInstructor(department As Department) If department.PersonID IsNot Nothing Then Dim duplicateDepartment = db.Departments. Include("Administrator"). Where(Function(d) d.PersonID = department.PersonID). AsNoTracking(). FirstOrDefault() If duplicateDepartment IsNot Nothing AndAlso duplicateDepartment.DepartmentID <> department.DepartmentID Then Dim errorMessage = String.Format("Instructor {0} {1} is already administrator of the {2} department.", duplicateDepartment.Administrator.FirstMidName, duplicateDepartment.Administrator.LastName, duplicateDepartment.Name) ModelState.AddModelError(String.Empty, errorMessage) End If End If End Sub

Page 15: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 15 of 44

Protected Overrides Sub Dispose(disposing As Boolean) db.Dispose() MyBase.Dispose(disposing) End Sub End Class End Namespace

Views

Delete

@ModelType ContosoUniversity.Department @Code ViewData("Title") = "Delete" End Code <h2>Delete</h2> <h3>Are you sure you want to delete this?</h3> <fieldset> <legend>Department</legend> <div class="display-label">Name</div> <div class="display-field"> @Html.DisplayFor(Function(model) model.Name) </div> <div class="display-label">Budget</div> <div class="display-field"> @Html.DisplayFor(Function(model) model.Budget) </div> <div class="display-label">Start Date</div> <div class="display-field"> @Html.DisplayFor(Function(model) model.StartDate) </div> <div class="display-label">Administrator</div> <div class="display-field"> @Html.DisplayFor(Function(model) model.Administrator.FullName) </div> </fieldset> @Using Html.BeginForm() @Html.HiddenFor(Function(model) model.DepartmentID) @Html.HiddenFor(Function(model) model.Timestamp) @<p> <input type="submit" value="Delete" /> | @Html.ActionLink("Back to List", "Index") </p> End Using

Page 16: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 16 of 44

Instructor

Screen - Index

Page 17: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 17 of 44

InstructorController – Index Code Imports System.Data.Entity Imports ContosoUniversity Namespace ContosoUniversity Public Class InstructorController Inherits System.Web.Mvc.Controller Private db As SchoolContext = New SchoolContext 'SchoolContext Inherits DbContext; it has Public Properties of DbSet's of ... ' Courses, Departments, Enrollments, Instructors, Students, People and OfficeAssignments ' ' GET: /Instructor/ ' InstructorIndexData has 3 IEnumerable public properties Instructors(), Courses() and Enrollments() ' Hierarchial list of Instructors, the selected courses they teach and students in the selected course

Public Function Index(id? As Int32, courseID? As Int32) As ActionResult Dim vmInstructorIndexData = New InstructorIndexData() 'This LINQ statement lasy loads (?) all the instructors, their courses, and their students. vmInstructorIndexData.Instructors = _ db.Instructors.Include( _ Function(i) i.Courses.Select(Function(c) c.Department) _ ).OrderBy(Function(i) i.LastName) ' Get a list of courses based on the Instructor ID If id IsNot Nothing Then ViewBag.PersonID = id.Value 'save this so the <tr class=""> value can be set to "selectedrow" vmInstructorIndexData.Courses = _ vmInstructorIndexData.Instructors.Where(Function(i) i.PersonID = id.Value).Single().Courses End If If courseID IsNot Nothing Then ViewBag.CourseID = courseID.Value 'save this so the <tr class=""> value can be set to "selectedrow" ' define a LINQ to objects object that will contain is a course subset of the view model Dim selectedCourse = _ vmInstructorIndexData.Courses.Where(Function(x) x.CourseID = courseID).Single() ' Load the course object db.Entry(selectedCourse).Collection(Function(x) x.Enrollments).Load() 'loop through the selected courses object and load the enrolled students using the "Reference" method For Each enrollment As Enrollment In selectedCourse.Enrollments db.Entry(enrollment).Reference(Function(x) x.Student).Load() 'What is reference. Next 'populate the enrolment as a subset of courses vmInstructorIndexData.Enrollments = _ vmInstructorIndexData.Courses.Where(Function(x) x.CourseID = courseID).Single().Enrollments End If Return View(vmInstructorIndexData) 'Return to the view, the view model End Function

Page 18: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 18 of 44

InstructorController – Other Non Edit Code ' ' GET: /Instructor/Details/5 Function Details(id As Integer) As ViewResult Dim instructor As Instructor = db.Instructors.Find(id) Return View(instructor) End Function ' ' GET: /Instructor/Create Function Create() As ViewResult Return View() End Function ' ' POST: /Instructor/Create <HttpPost()> Function Create(instructor As Instructor) As ActionResult If ModelState.IsValid Then db.Instructors.Add(instructor) db.SaveChanges() Return RedirectToAction("Index") End If Return View(instructor) End Function . . . . . See Edit Code ' ' GET: /Instructor/Delete/5 Function Delete(id As Integer) As ViewResult Dim instructor As Instructor = db.Instructors.Find(id) Return View(instructor) End Function ' ' POST: /Instructor/Delete/5 <HttpPost()> <ActionName("Delete")> Function DeleteConfirmed(id As Integer) As RedirectToRouteResult Dim instructor As Instructor = db.Instructors.Find(id) db.Instructors.Remove(instructor) db.SaveChanges() Return RedirectToAction("Index") End Function Protected Overrides Sub Dispose(disposing As Boolean) db.Dispose() MyBase.Dispose(disposing) End Sub End Class End Namespace

Page 19: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 19 of 44

ViewModels\InstructorIndexData Imports System.Collections.Generic Public Class InstructorIndexData Public Property Instructors() As IEnumerable(Of Instructor) Public Property Courses() As IEnumerable(Of Course) Public Property Enrollments() As IEnumerable(Of Enrollment) End Class

View\Index @ModelType ContosoUniversity.InstructorIndexData @Code ViewData("Title") = "Instructors" End Code <h2>Instructors</h2> <p> @Html.ActionLink("Create New", "Create") </p> <table> <tr> <th></th> <th>Last Name</th> <th>First Name</th> <th>Hire Date</th> <th>Office</th> <th>Courses</th> </tr> @For Each item In Model.Instructors Dim currentItem = item Dim selectedRow As String = "" If item.PersonID = ViewBag.PersonID Then selectedRow = "selectedrow" End If @<tr class="@selectedRow" valign="top"> <td> @Html.ActionLink("Select", "Index", New With {.id = currentItem.PersonID}) | @Html.ActionLink("Edit", "Edit", New With {.id = currentItem.PersonID}) | @Html.ActionLink("Details", "Details", New With {.id = currentItem.PersonID}) | @Html.ActionLink("Delete", "Delete", New With {.id = currentItem.PersonID}) </td> <td> @Html.DisplayFor(Function(modelItem) currentItem.LastName) </td> <td> @Html.DisplayFor(Function(modelItem) currentItem.FirstMidName) </td> <td> @Html.DisplayFor(Function(modelItem) currentItem.HireDate) </td> <td> @Html.DisplayFor(Function(modelItem) currentItem.OfficeAssignment.Location) </td> <td> @Code For Each course As ContosoUniversity.Course In item.Courses @course.CourseID @:&nbsp; @course.Title <br /> Next End Code </td> </tr> Next </table>

Page 20: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 20 of 44

' Make an html table of course if they exist @If Model.Courses IsNot Nothing Then @<h3>Courses Taught by Selected Instructor</h3> @<table> <tr> <th></th> <th>ID</th> <th>Title</th> <th>Department</th> </tr> @For Each item As ContosoUniversity.Course In Model.Courses Dim selectedRow As String = "" If item.CourseID = ViewBag.CourseID Then selectedRow = "selectedrow" End If @<tr class="@selectedRow"> <td> @Html.ActionLink("Select", "Index", New With {.courseID = item.CourseID}) </td> <td> @item.CourseID </td> <td> @item.Title </td> <td> @item.Department.Name </td> </tr> Next </table> End If ' Make an html table of enrollments if they exist @If Model.Enrollments IsNot Nothing Then @<h3>Students Enrolled in Selected Course</h3> @<table> <tr> <th>Name</th> <th>Grade</th> </tr> @For Each item As ContosoUniversity.Enrollment In Model.Enrollments @<tr> <td> @item.Student.FullName </td> <td> @item.Grade </td> </tr> Next </table> End If

Page 21: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 21 of 44

Screen - Edit

Page 22: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 22 of 44

InstructorController – Edit Code ' ' GET: /Instructor/Edit/5 Public Function Edit(id As Integer) As ActionResult Dim instructor As Instructor = db.Instructors. Include(Function(i) i.Courses). Where(Function(i) i.PersonID = id). Single() PopulateAssignedCourseData(instructor) Return View(instructor) End Function 'Called by Edit and Edit Post

Private Sub PopulateAssignedCourseData(instructor As Instructor) Dim allCourses = db.Courses ' Public Property Courses() As DbSet(Of Course) 'HashSet, what does this do? Dim instructorCourses = New HashSet(Of Integer)(instructor.Courses.Select(Function(c) c.CourseID)) 'AssignedCourseData is simple clase with Public Properties for CourseID, Title and Assigned (y/n) Dim vmAssignedCourseData = New List(Of AssignedCourseData)() ' Loop thru the courses For Each course As Course In allCourses vmAssignedCourseData.Add(New AssignedCourseData() With { _ .CourseID = course.CourseID, _ .Title = course.Title, _ .Assigned = instructorCourses.Contains(course.CourseID) _ }) Next ViewBag.Courses = vmAssignedCourseData End Sub

Page 23: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 23 of 44

Page 24: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 24 of 44

' ' POST: /Instructor/Edit/5 <HttpPost()> _ Public Function Edit(id As Integer, _ formCollection As FormCollection, _ selectedCourses As String()) As ActionResult ' Dim instructorToUpdate = _ db.Instructors.Include(Function(i) i.Courses).Where(Function(i) i.PersonID = id).Single() Try UpdateModel(instructorToUpdate, "", Nothing, New String() {"Courses"}) If String.IsNullOrWhiteSpace(instructorToUpdate.OfficeAssignment.Location) Then instructorToUpdate.OfficeAssignment = Nothing End If UpdateInstructorCourses(selectedCourses, instructorToUpdate) db.Entry(instructorToUpdate).State = EntityState.Modified db.SaveChanges() Return RedirectToAction("Index") Catch ex As DataException 'Log the error ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, contact your system administrator.") End Try PopulateAssignedCourseData(instructorToUpdate) Return View(instructorToUpdate) End Function 'Called by Edit Post Private Sub UpdateInstructorCourses(selectedCourses As String(), instructorToUpdate As Instructor) If selectedCourses Is Nothing Then instructorToUpdate.Courses = New List(Of Course)() Return End If Dim selectedCoursesHS = New HashSet(Of String)(selectedCourses) Dim instructorCourses = New HashSet(Of Integer)(instructorToUpdate.Courses.Select(Function(c) c.CourseID)) For Each course As Course In db.Courses If selectedCoursesHS.Contains(course.CourseID.ToString()) Then If Not instructorCourses.Contains(course.CourseID) Then instructorToUpdate.Courses.Add(course) End If Else If instructorCourses.Contains(course.CourseID) Then instructorToUpdate.Courses.Remove(course) End If End If Next End Sub

Page 25: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 25 of 44

ViewModels\AssignedCourseData Imports System.Collections.Generic 'Imports System.ComponentModel.DataAnnotations 'Simple clase with Public Properties of CourseID, Title, Assigned (y/n) Public Class AssignedCourseData Public Property CourseID() As Integer Public Property Title() As String Public Property Assigned() As Boolean End Class

View\Edit @ModelType ContosoUniversity.Instructor @Code ViewData("Title") = "Edit" End Code <h2>Edit</h2> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> @Using Html.BeginForm() @Html.ValidationSummary(True) @<fieldset> <legend>Instructor</legend> @Html.HiddenFor(Function(model) model.PersonID) <div class="editor-label"> @Html.LabelFor(Function(model) model.LastName) </div> <div class="editor-field"> @Html.EditorFor(Function(model) model.LastName) @Html.ValidationMessageFor(Function(model) model.LastName) </div> <div class="editor-label"> @Html.LabelFor(Function(model) model.FirstMidName) </div> <div class="editor-field"> @Html.EditorFor(Function(model) model.FirstMidName) @Html.ValidationMessageFor(Function(model) model.FirstMidName) </div> <div class="editor-label"> @Html.LabelFor(Function(model) model.HireDate) </div> <div class="editor-field"> @Html.EditorFor(Function(model) model.HireDate) @Html.ValidationMessageFor(Function(model) model.HireDate) </div> <div class="editor-label"> @Html.LabelFor(Function(model) model.OfficeAssignment.Location)

Page 26: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 26 of 44

</div> <div class="editor-field"> @Html.EditorFor(Function(model) model.OfficeAssignment.Location) @Html.ValidationMessageFor(Function(model) model.OfficeAssignment.Location) </div>

<div class="editor-label"> @Html.LabelFor(Function(model) model.Courses) </div> <div class="editor-field"> <table style="width: 100%"> <tr> @Code Dim cnt as Integer = 0 'ViewBag.Courses = vmAssignedCourseData Dim courses As List(Of ContosoUniversity.AssignedCourseData) = ViewBag.Courses For Each course As ContosoUniversity.AssignedCourseData In courses If cnt Mod 3 = 0 Then 'this makes a 3 up column @:</tr> <tr> End If cnt += 1 @<td> <input type="checkbox" name="selectedCourses" [email protected](("""" & course.CourseID & """")) @IIf(course.Assigned, "checked =""checked""", "") /> @course.CourseID &nbsp; @course.Title </td> Next @:</tr> End Code </table> </div> <p> <input type="submit" value="Save" /> </p> </fieldset> End Using <div> @Html.ActionLink("Back to List", "Index") </div>

Page 27: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 27 of 44

View Source . . . . <div class="editor-field"> <table style="width: 100%"> <tr> </tr> <tr> <td> <input type="checkbox" name="selectedCourses" value="1045" /> 1045 &nbsp; Calculus </td> <td> <input type="checkbox" name="selectedCourses" value="1050" /> 1050 &nbsp; Chemistry </td> <td> <input type="checkbox" name="selectedCourses" value="2021" /> 2021 &nbsp; Composition </td> </tr> <tr> <td> <input type="checkbox" name="selectedCourses" value="2042" checked =&quot;checked&quot; /> 2042 &nbsp; Literature </td> <td> <input type="checkbox" name="selectedCourses" value="3141" /> 3141 &nbsp; Trigonometry </td> <td> <input type="checkbox" name="selectedCourses" value="4022" checked =&quot;checked&quot; /> 4022 &nbsp; Microeconomics </td> </tr> <tr> <td> <input type="checkbox" name="selectedCourses" value="4041" checked =&quot;checked&quot; /> 4041 &nbsp; Macroeconomics </td> </tr> </table> </div>

. . . .

Page 28: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 28 of 44

Student

SchoolContext {code related to Student} Imports System.Collections.Generic Imports System.Data.Entity Public Class SchoolContext Inherits DbContext 'System.Data.Entity … Public Property Students() As DbSet(Of Student) … 'DbModelBuilder is used to map CLR classes to a database schema (Code First). ... End Sub End Class

IStudentRepository and StudentRepository

Public Interface IStudentRepository Inherits IDisposable Function GetStudents() As IEnumerable(Of Student) Function GetStudentByID(id As Integer) As Student Sub InsertStudent(student As Student) Sub DeleteStudent(studentID As Integer) Sub UpdateStudent(student As Student) Sub Save() End Interface Imports System.Collections.Generic Imports System.Linq Imports System.Data

Public Class StudentRepository Implements IStudentRepository Implements IDisposable Private context As SchoolContext Public Sub New(context As SchoolContext) Me.context = context End Sub Public Function GetStudents() As IEnumerable(Of Student) Implements IStudentRepository.GetStudents Return context.Students.ToList() End Function Public Function GetStudentByID(studentId As Integer) As Student Implements IStudentRepository.GetStudentByID Return context.Students.Find(studentId) End Function Public Sub InsertStudent(student As Student) Implements IStudentRepository.InsertStudent context.Students.Add(student) End Sub Public Sub DeleteStudent(studentID As Integer) Implements IStudentRepository.DeleteStudent Dim student As Student = context.Students.Find(studentID)

Page 29: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 29 of 44

context.Students.Remove(student) End Sub Public Sub UpdateStudent(student As Student) Implements IStudentRepository.UpdateStudent context.Entry(student).State = EntityState.Modified End Sub Public Sub Save() Implements IStudentRepository.Save context.SaveChanges() End Sub Private disposed As Boolean = False Protected Overridable Sub Dispose(disposing As Boolean) If Not Me.disposed Then If disposing Then context.Dispose() End If End If Me.disposed = True End Sub Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub End Class

StudentController

StudentController – Dependency Injection Related Code

Imports System.Data.Entity Imports ContosoUniversity Imports PagedList Namespace ContosoUniversity Public Class StudentController Inherits System.Web.Mvc.Controller Private studentRepository As IStudentRepository Public Sub New() Me.studentRepository = New StudentRepository(New SchoolContext()) End Sub Public Sub New(studentRepository As IStudentRepository) Me.studentRepository = studentRepository End Sub

Page 30: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 30 of 44

Screen - Index

Page 31: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 31 of 44

StudentController – Index Code

' ' GET: /Student/

Public Function Index(sortOrder As String, currentFilter As String, _ searchString As String, page? As Integer) As ViewResult ViewBag.CurrentSort = sortOrder ViewBag.NameSortParm = IIf(String.IsNullOrEmpty(sortOrder), "Name desc", "") ViewBag.DateSortParm = IIf(sortOrder = "Date", "Date desc", "Date") '? If Request.HttpMethod = "GET" Then searchString = currentFilter Else page = 1 ViewBag.CurrentFilter = searchString Dim students = From s In studentRepository.GetStudents() 'Return context.Students.ToList() If Not String.IsNullOrEmpty(searchString) Then ' reload the students list object from a subset of itself using the search string students = students. Where(Function(s) s.LastName.ToUpper().Contains(searchString.ToUpper()) _ OrElse s.FirstMidName.ToUpper().Contains(searchString.ToUpper())) End If Select Case sortOrder Case "Name desc" students = students.OrderByDescending(Function(s) s.LastName) Exit Select Case "Date" students = students.OrderBy(Function(s) s.EnrollmentDate) Exit Select Case "Date desc" students = students.OrderByDescending(Function(s) s.EnrollmentDate) Exit Select Case Else students = students.OrderBy(Function(s) s.LastName) Exit Select End Select Dim pageSize As Integer = 3 Dim pageIndex As Integer = (If(page, 1)) - 1 Return View(students.ToPagedList(pageIndex, pageSize)) End Function

Page 32: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 32 of 44

View\Index @ModelType PagedList.IPagedList(Of ContosoUniversity.Student) @Code ViewData("Title") = "Students" End Code <h2>Students</h2> <p> @Html.ActionLink("Create New", "Create") </p> @Using Html.BeginForm() @<p> Find by name: @Html.TextBox("SearchString", ViewBag.CurrentFilter) &nbsp; <input type="submit" value="Search" /></p> End Using <table> <tr> <th></th> <th> @Html.ActionLink("Last Name", "Index", New With {.sortOrder = ViewBag.NameSortParm, .currentFilter = ViewBag.CurrentFilter}) </th> <th> First Name</th> <th> @Html.ActionLink("Enrollment Date", "Index", New With {.sortOrder = ViewBag.DateSortParm, .currentFilter = ViewBag.CurrentFilter}) </th> </tr>

Page 33: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 33 of 44

@For Each item In Model Dim currentItem = item @<tr> <td> @Html.ActionLink("Edit", "Edit", New With {.id = currentItem.PersonID}) | @Html.ActionLink("Details", "Details", New With {.id = currentItem.PersonID}) | @Html.ActionLink("Delete", "Delete", New With {.id = currentItem.PersonID}) </td> <td> @Html.DisplayFor(Function(modelItem) currentItem.LastName) </td> <td> @Html.DisplayFor(Function(modelItem) currentItem.FirstMidName) </td> <td> @Html.DisplayFor(Function(modelItem) currentItem.EnrollmentDate) </td> </tr> Next </table> <div> Page @(IIf(Model.PageCount < Model.PageNumber, 0, Model.PageNumber)) of @Model.PageCount &nbsp; @If Model.HasPreviousPage Then @Html.ActionLink("<<", "Index", New With {.page = 1, .sortOrder = ViewBag.CurrentSort, .currentFilter = ViewBag.CurrentFilter}) @Html.Raw("&nbsp;") @Html.ActionLink("< Prev", "Index", New With {.page = Model.PageNumber - 1, .sortOrder = ViewBag.CurrentSort, .currentFilter = ViewBag.CurrentFilter}) Else @:<< @Html.Raw("&nbsp;") @:< Prev End If &nbsp; @If Model.HasNextPage Then @Html.ActionLink("Next >", "Index", New With {.page = Model.PageNumber + 1, .sortOrder = ViewBag.CurrentSort, .currentFilter = ViewBag.CurrentFilter}) @Html.Raw("&nbsp;") @Html.ActionLink(">>", "Index", New With {.page = Model.PageCount, .sortOrder = ViewBag.CurrentSort, .currentFilter = ViewBag.CurrentFilter}) Else @:Next > @Html.Raw("&nbsp;") @:>> End If </div>

Page 34: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 34 of 44

Home

HomeController Public Class HomeController Inherits System.Web.Mvc.Controller Private db As SchoolContext = New SchoolContext Function Index() As ActionResult ViewData("Message") = "Welcome to Contoso University!" Return View() End Function Function About() As ActionResult Dim query = "SELECT EnrollmentDate, COUNT(*) AS StudentCount " & "FROM Person " & "WHERE EnrollmentDate IS NOT NULL " & "GROUP BY EnrollmentDate" Dim data = db.Database.SqlQuery(Of EnrollmentDateGroup)(query) Return View(data) End Function End Class

ViewModels\EnrollmentDateGroup Imports System.Collections.Generic Imports System.ComponentModel.DataAnnotations Public Class EnrollmentDateGroup <DisplayFormat(DataFormatString:="{0:d}")> _ Public Property EnrollmentDate() As System.Nullable(Of DateTime) Public Property StudentCount() As Integer End Class Imports System.Collections.Generic Imports System.ComponentModel.DataAnnotations Public Class Enrollment Public Property EnrollmentID() As Integer Public Property CourseID() As Integer Public Property PersonID() As Integer <DisplayFormat(DataFormatString:="{0:#.#}", ApplyFormatInEditMode:=True, NullDisplayText:="No grade")> _ Public Property Grade() As System.Nullable(Of Decimal) Public Overridable Property Course() As Course Public Overridable Property Student() As Student End Class

Page 35: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 35 of 44

Views\Home\About @ModelType IEnumerable (of ContosoUniversity.EnrollmentDateGroup) @Code ViewBag.Title = "Student Body Statistics" End code <h2>Student Body Statistics</h2> <table> <tr> <th> Enrollment Date </th> <th> Students </th> </tr> @For Each item As ContosoUniversity.EnrollmentDateGroup In Model @<tr> <td> @String.Format("{0:d}", item.EnrollmentDate) </td> <td> @item.StudentCount </td> </tr> Next </table>

Screen - About

Page 36: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 36 of 44

SchoolInitializer

Imports System.Collections.Generic Imports System.Linq Imports System.Web Imports System.Data.Entity Public Class SchoolInitializer Inherits DropCreateDatabaseIfModelChanges(Of SchoolContext) Protected Overrides Sub Seed(context As SchoolContext) Dim students = New List(Of Student)() From { _ New Student() With { _ .FirstMidName = "Carson", .LastName = "Alexander", _ .EnrollmentDate = DateTime.Parse("2005-09-01") _ }, _ New Student() With { _ .FirstMidName = "Meredith", _ .LastName = "Alonso", _ .EnrollmentDate = DateTime.Parse("2002-09-01") _ }, _ . . . } students.ForEach(Function(s) context.Students.Add(s)) context.SaveChanges() Dim instructors = New List(Of Instructor)() From { _ New Instructor() With { _ .FirstMidName = "Kim", _ .LastName = "Abercrombie", _ .HireDate = DateTime.Parse("1995-03-11") _ }, _ . . . } instructors.ForEach(Function(s) context.Instructors.Add(s)) context.SaveChanges() Dim departments = New List(Of Department)() From { _ New Department() With { _ .Name = "English", _ .Budget = 350000, _ .StartDate = DateTime.Parse("2007-09-01"), _ .PersonID = 9 _ }, _ . . . } departments.ForEach(Function(s) context.Departments.Add(s)) context.SaveChanges() Dim courses = New List(Of Course)() From { _ New Course() With { _ .CourseID = 1050, _ .Title = "Chemistry", _ .Credits = 3, _ .DepartmentID = 3, _ .Instructors = New List(Of Instructor)() _ }, _ . . . } courses.ForEach(Function(s) context.Courses.Add(s))

Page 37: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 37 of 44

context.SaveChanges() courses(0).Instructors.Add(instructors(0)) . . . courses(6).Instructors.Add(instructors(3)) context.SaveChanges() Dim enrollments = New List(Of Enrollment)() From { _ New Enrollment() With { _ .PersonID = 1, _ .CourseID = 1050, _ .Grade = 1 _ }, _ . . . } enrollments.ForEach(Function(s) context.Enrollments.Add(s)) context.SaveChanges() Dim officeAssignments = New List(Of OfficeAssignment)() From { _ New OfficeAssignment() With { _ .PersonID = 9, _ .Location = "Smith 17" _ }, _ . . . } officeAssignments.ForEach(Function(s) context.OfficeAssignments.Add(s)) context.SaveChanges() End Sub End Class

Packages.config

<?xml version="1.0" encoding="utf-8"?> <packages> <package id="jQuery" version="1.4.4" /> <package id="jQuery.Validation" version="1.7" /> <package id="jQuery.UI.Combined" version="1.8.7" /> <package id="EntityFramework" version="4.1.10311.0" /> <package id="Modernizr" version="1.7" /> <package id="PagedList" version="1.2.1.0" /> </packages>

Page 38: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 38 of 44

My Notes on the Repository

GenericRepository - Summary

- Is a Generic Class (ironically of t where t is a Class) see.

- Like a base class but isn’t because it doesn’t use MustInherit

- Used by CourseRepository as a base class

- Used twice by UnitOfWork as a private variable, examples…

Directly Private _departmentRepository As GenericRepository(Of Department)

Indirectly Private _courseRepository As CourseRepositor

- All of it’s methods are overidable

[Get] GetByID Public Overridable Function GetByID(id As Object) As TEntity

Return dbSet.Find(id) End Function

Insert Public Overridable Sub Insert(entity As TEntity) dbSet.Add(entity) End Sub

Delete(1) Public Overridable Sub Delete(id As Object) Dim entityToDelete As TEntity = dbSet.Find(id) Delete(entityToDelete) End Sub

Delete(2) Public Overridable Sub Delete(entityToDelete As TEntity) If context.Entry(entityToDelete).State = EntityState.Detached Then dbSet.Attach(entityToDelete) End If dbSet.Remove(entityToDelete) End Sub

Update Public Overridable Sub Update(entityToUpdate As TEntity) dbSet.Attach(entityToUpdate) context.Entry(entityToUpdate).State = EntityState.Modified End Sub

GetWithRawSql Public Overridable Function GetWithRawSql( query As String, ParamArray parameters As Object()) As IEnumerable(Of TEntity) Return dbSet.SqlQuery(Query, parameters).ToList() End Function

- Uses a Class parameter in the Class definition

- Uses two Friend members (like Public to elements inside the assembly), context and dbset

Public Class GenericRepository(Of TEntity As Class) Friend context As SchoolContext Friend dbSet As DbSet(Of TEntity) Public Sub New(context As SchoolContext) Me.context = context Me.dbSet = context.Set(Of TEntity)() End Sub

Page 39: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 39 of 44

CourseRepository 'UnitOfWork wraps CourseRepository

Public Class CourseRepository Inherits GenericRepository(Of Course) Public Sub New(context As SchoolContext)

MyBase.New(context) 'behaves like an object variable referring to the base class End Sub

'Note: Not Referenced

Public Function UpdateCourseCredits(multiplier As Integer) As Integer Return context.Database.ExecuteSqlCommand( _ "UPDATE Course SET Credits = Credits * {0}", multiplier) End Function End Class

IStudentRepository

- (Inherits IDisposable), - Used lot's of places, See Also

StudentRepository - Summary

- Implements IStudentRepository and Implements IDisposable

- Used By StudentController

Imports System.Collections.Generic Imports System.Linq Imports System.Data Public Class StudentRepository Implements IStudentRepository Implements IDisposable Private context As SchoolContext Public Sub New(context As SchoolContext) Me.context = context End Sub . . .

StudentController

Imports System.Data.Entity Imports ContosoUniversity Imports PagedList Namespace ContosoUniversity Public Class StudentController Inherits System.Web.Mvc.Controller Private studentRepository As IStudentRepository Public Sub New() Me.studentRepository = New StudentRepository(New SchoolContext()) End Sub Public Sub New(studentRepository As IStudentRepository) Me.studentRepository = studentRepository End Sub

Page 40: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 40 of 44

SchoolContext Imports System.Collections.Generic Imports System.Data.Entity Imports System.Data.Entity.ModelConfiguration.Conventions Public Class SchoolContext Inherits DbContext 'System.Data.Entity Public Property Courses() As DbSet(Of Course) Public Property Departments() As DbSet(Of Department) Public Property Enrollments() As DbSet(Of Enrollment) Public Property Instructors() As DbSet(Of Instructor) Public Property Students() As DbSet(Of Student) Public Property People() As DbSet(Of Person) Public Property OfficeAssignments() As DbSet(Of OfficeAssignment) 'DbModelBuilder is used to map CLR classes to a database schema (Code First). Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder) modelBuilder.Conventions.Remove(Of PluralizingTableNameConvention)() modelBuilder.Entity(Of Instructor)(). HasOptional(Function(p) p.OfficeAssignment). WithRequired(Function(p) p.Instructor) modelBuilder.Entity(Of Course)(). HasMany(Function(c) c.Instructors). WithMany(Function(i) i.Courses). Map(Function(t) t.MapLeftKey("CourseID"). MapRightKey("PersonID"). ToTable("CourseInstructor")) modelBuilder.Entity(Of Department)().HasOptional(Function(x) x.Administrator) End Sub End Class

JKM: Could I make the relationship between ParashaHeader and SeriesReadingList using HasOptional?

UnitOfWork Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the

resolution of concurrency problems

When you're pulling data in and out of a database, it's important to keep track of what you've changed; otherwise, that data

won't be written back into the database. Similarly you have to insert new objects you create and remove any objects you

delete.

You can change the database with each change to your object model, but this can lead to lots of very small database calls,

which ends up being very slow. Furthermore it requires you to have a transaction open for the whole interaction, which is

impractical if you have a business transaction that spans multiple requests. The situation is even worse if you need to keep track of the objects you've read so you can avoid inconsistent reads.

A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you're

done, it figures out everything that needs to be done to alter the database as a result of your work.

Public Class UnitOfWork Implements IDisposable Private context As New SchoolContext() Private _departmentRepository As GenericRepository(Of Department) Private _courseRepository As CourseRepository

Page 41: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 41 of 44

'Used by CourseController ' Index... ' Dim departments = unitOfWork.DepartmentRepository.Get(orderBy:=Function(q) q.OrderBy(Function(d) d.Name)) ' PopulateDepartmentsDropDownList... ' Dim departmentsQuery = unitOfWork.DepartmentRepository.Get(orderBy:=Function(q) q.OrderBy(Function(d) d.Name)) Public ReadOnly Property DepartmentRepository() As GenericRepository(Of Department) Get If Me._departmentRepository Is Nothing Then Me._departmentRepository = New GenericRepository(Of Department)(context) End If Return _departmentRepository End Get End Property 'Used by CourseController ' Index: Return View(unitOfWork.CourseRepository.Get(... ' Details: Return View(unitOfWork.CourseRepository.GetWithRawSql(query, id).Single()) ' Create: unitOfWork.CourseRepository.Insert(course) ' Edit: Dim course As Course = unitOfWork.CourseRepository.GetByID(id) ' Edit(2): unitOfWork.CourseRepository.Update(course) ' Delete: Dim course As Course = unitOfWork.CourseRepository.GetByID(id) ' Delete(2): unitOfWork.CourseRepository.Delete(id) Public ReadOnly Property CourseRepository() As CourseRepository Get If Me._courseRepository Is Nothing Then Me._courseRepository = New CourseRepository(context) End If Return _courseRepository End Get End Property Public Sub Save() context.SaveChanges() End Sub Private disposed As Boolean = False Protected Overridable Sub Dispose(disposing As Boolean) If Not Me.disposed Then If disposing Then context.Dispose() End If End If Me.disposed = True End Sub Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) 'System.GC = Garbage Collector End Sub End Class

Page 42: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 42 of 44

GenericRepository - Detail Imports System.Collections.Generic Imports System.Linq Imports System.Data Imports System.Data.Entity Imports System.Linq.Expressions '************************************************************************************************ ' Used By... ' CourseRepository ' - Inherits GenericRepository(Of Course) ' ' UnitOfWork ' - Private _departmentRepository As GenericRepository(Of Department) ' - Public ReadOnly Property DepartmentRepository() As GenericRepository(Of Department) ' - Me._departmentRepository = New GenericRepository(Of Department)(context) '************************************************************************************************ Public Class GenericRepository(Of TEntity As Class) Friend context As SchoolContext 'Friends is like Public to elements inside the assembly Friend dbSet As DbSet(Of TEntity) Public Sub New(context As SchoolContext) Me.context = context Me.dbSet = context.Set(Of TEntity)() ' End Sub 'Used by CourseController ' Index ' Dim departments = UnitOfWork.DepartmentRepository.Get(orderBy:=Function(q) q.OrderBy(Function(d) d.Name)) ' Return View(unitOfWork.CourseRepository.Get( ' filter:=Function(d) Not SelectedDepartment.HasValue OrElse d.DepartmentID = departmentID, ' orderBy:=Function(q) q.OrderBy(Function(d) d.CourseID), ' includeProperties:="Department")) ' ' PopulateDepartmentsDropDownList: ' Dim departmentsQuery = unitOfWork.DepartmentRepository.Get(orderBy:=Function(q)...

Public Overridable Function [Get]( Optional filter As Expression(Of Func(Of TEntity, Boolean)) = Nothing, Optional orderBy As Func(Of IQueryable(Of TEntity), IOrderedQueryable(Of TEntity)) = Nothing, Optional includeProperties As String = "") As IEnumerable(Of TEntity) Dim query As IQueryable(Of TEntity) = dbSet If filter IsNot Nothing Then query = query.Where(filter) End If For Each includeProperty As String In includeProperties.Split(New Char() {","c}, StringSplitOptions.RemoveEmptyEntries) query = query.Include(includeProperty) Next If orderBy IsNot Nothing Then Return orderBy(query).ToList() Else Return query.ToList() End If End Function

Page 43: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 43 of 44

'Used by CourseController Edit & Delete: Dim course As Course = unitOfWork.CourseRepository.GetByID(id) Public Overridable Function GetByID(id As Object) As TEntity Return dbSet.Find(id) End Function 'Used by CourseController!Create: unitOfWork.CourseRepository.Insert(course) Public Overridable Sub Insert(entity As TEntity) dbSet.Add(entity) End Sub 'Used by CourseController Public Overridable Sub Delete(id As Object) Dim entityToDelete As TEntity = dbSet.Find(id) Delete(entityToDelete) End Sub Public Overridable Sub Delete(entityToDelete As TEntity) If context.Entry(entityToDelete).State = EntityState.Detached Then dbSet.Attach(entityToDelete) End If dbSet.Remove(entityToDelete) End Sub Public Overridable Sub Update(entityToUpdate As TEntity) dbSet.Attach(entityToUpdate) context.Entry(entityToUpdate).State = EntityState.Modified End Sub Public Overridable Function GetWithRawSql(query As String, ParamArray parameters As Object()) As IEnumerable(Of TEntity) Return dbSet.SqlQuery(Query, parameters).ToList() End Function End Class

Page 44: Contoso University MVC 3 Sample Project - … · Contoso University MVC 3 Sample Project ... Framework in an ASP.NET MVC web application project, using the ... To build and run this

12/5/2012 http://torahlawform.com/Documents/ 44 of 44

DbSet(Of TEntity)

Set(Of TEntity As Class)()

Public Function [Set](Of TEntity As Class)() As System.Data.Entity.DbSet(Of TEntity)

Member of System.Data.Entity.DbContext

Summary: Returns a DbSet instance for access to entities of the given type in the context, the

ObjectStateManager, and the underlying store.

Type parameters: TEntity: The type entity for which a set should be returned.

Return Values: A set for the given entity type.


Recommended