MVC与EF结合:Contoso大学
中文教程
1、通过 MVC 5 使用 Entity Framework 6 Code First 入门
2、通过 MVC 4 使用 Entity Framework 5 Code First 入门
3、通过 ASP.NET Core MVC 使用 Entity Framework Core 入门
https://docs.microsoft.com/zh-cn/aspnet/core/data/ef-mvc/?view=aspnetcore-2.1
示例源码下载
1、Contoso University - Entity Framework 6 and ASP.NET MVC 5
https://code.msdn.microsoft.com/ASPNET-MVC-Application-b01a9fe8
2、Contoso University - Entity Framework Core in an ASP.NET Core MVC
https://github.com/aspnet/Docs/tree/master/aspnetcore/data/ef-mvc/intro/samples/cu-final
一、Models:模型

public abstract class Person
{
[Key]
public int PersonID { get; set; } [Required(ErrorMessage = "Last name is required.")]
[Display(Name = "Last Name")]
[MaxLength()]
public string LastName { get; set; } [Required(ErrorMessage = "First name is required.")]
[Column("FirstName")]
[Display(Name = "First Name")]
[MaxLength()]
public string FirstMidName { get; set; } public string FullName
{
get
{
return LastName + ", " + FirstMidName;
}
}
}
public class Student : Person
{
[Required(ErrorMessage = "Enrollment date is required.")]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[Display(Name = "Enrollment Date")]
public DateTime? EnrollmentDate { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; }
}
public class Enrollment
{
public int EnrollmentID { get; set; } public int CourseID { get; set; } public int PersonID { get; set; } [DisplayFormat(DataFormatString = "{0:#.#}", ApplyFormatInEditMode = true, NullDisplayText = "No grade")]
public decimal? Grade { get; set; } public virtual Course Course { get; set; }
public virtual Student Student { get; set; }
}
public class Course
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Display(Name = "Number")]
public int CourseID { get; set; } [Required(ErrorMessage = "Title is required.")]
[MaxLength()]
public string Title { get; set; } [Required(ErrorMessage = "Number of credits is required.")]
[Range(, , ErrorMessage = "Number of credits must be between 0 and 5.")]
public int Credits { get; set; } [Display(Name = "Department")]
public int DepartmentID { get; set; } public virtual Department Department { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
public virtual ICollection<Instructor> Instructors { get; set; }
}
public class Department
{
public int DepartmentID { get; set; } [Required(ErrorMessage = "Department name is required.")]
[MaxLength()]
public string Name { get; set; } [DisplayFormat(DataFormatString = "{0:c}")]
[Required(ErrorMessage = "Budget is required.")]
[Column(TypeName = "money")]
public decimal? Budget { get; set; } [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[Required(ErrorMessage = "Start date is required.")]
public DateTime StartDate { get; set; } [Display(Name = "Administrator")]
public int? PersonID { get; set; } [Timestamp]
public Byte[] Timestamp { get; set; } public virtual Instructor Administrator { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
public class Instructor : Person
{
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[Required(ErrorMessage = "Hire date is required.")]
[Display(Name = "Hire Date")]
public DateTime? HireDate { get; set; } public virtual ICollection<Course> Courses { get; set; } public virtual OfficeAssignment OfficeAssignment { get; set; }
}
public class OfficeAssignment
{
[Key]
public int PersonID { get; set; } [MaxLength()]
[Display(Name = "Office Location")]
public string Location { get; set; } public virtual Instructor Instructor { get; set; }
}
二、控制器
public class InstructorController : Controller
{
private SchoolContext db = new SchoolContext(); public ActionResult Index(Int32? id, Int32? courseID) // GET: /Instructor/
{
var viewModel = new InstructorIndexData();
viewModel.Instructors = db.Instructors
.Include(i => i.Courses.Select(c => c.Department))
.OrderBy(i => i.LastName);
if (id != null)
{
ViewBag.PersonID = id.Value;
viewModel.Courses = viewModel.Instructors.Where(i => i.PersonID == id.Value).Single().Courses;
}
if (courseID != null)
{
ViewBag.CourseID = courseID.Value;
var selectedCourse = viewModel.Courses.Where(x => x.CourseID == courseID).Single();
db.Entry(selectedCourse).Collection(x => x.Enrollments).Load();
foreach (Enrollment enrollment in selectedCourse.Enrollments)
{
db.Entry(enrollment).Reference(x => x.Student).Load();
}
viewModel.Enrollments = selectedCourse.Enrollments;
}
return View(viewModel);
} public ViewResult Details(int id) // GET: /Instructor/Details/5
{
Instructor instructor = db.Instructors.Find(id);
return View(instructor);
} public ActionResult Create() // GET: /Instructor/Create
{
ViewBag.PersonID = new SelectList(db.OfficeAssignments, "PersonID", "Location");
return View();
} [HttpPost]
public ActionResult Create(Instructor instructor) // POST: /Instructor/Create
{
if (ModelState.IsValid)
{
db.Instructors.Add(instructor);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.PersonID = new SelectList(db.OfficeAssignments, "PersonID", "Location", instructor.PersonID);
return View(instructor);
} public ActionResult Edit(int id) // GET: /Instructor/Edit/5
{
Instructor instructor = db.Instructors
.Include(i => i.Courses)
.Where(i => i.PersonID == id)
.Single();
PopulateAssignedCourseData(instructor);
return View(instructor);
} private void PopulateAssignedCourseData(Instructor instructor)
{
var allCourses = db.Courses;
var instructorCourses = new HashSet<int>(instructor.Courses.Select(c => c.CourseID));
var viewModel = new List<AssignedCourseData>();
foreach (var course in allCourses)
{
viewModel.Add(new AssignedCourseData
{
CourseID = course.CourseID,
Title = course.Title,
Assigned = instructorCourses.Contains(course.CourseID)
});
}
ViewBag.Courses = viewModel;
} [HttpPost]
public ActionResult Edit(int id, FormCollection formCollection, string[] selectedCourses) // POST: /Instructor/Edit/5
{
var instructorToUpdate = db.Instructors
.Include(i => i.Courses)
.Where(i => i.PersonID == id)
.Single();
if (TryUpdateModel(instructorToUpdate, "", null, new string[] { "Courses" }))
{
try
{
if (String.IsNullOrWhiteSpace(instructorToUpdate.OfficeAssignment.Location))
{
instructorToUpdate.OfficeAssignment = null;
}
UpdateInstructorCourses(selectedCourses, instructorToUpdate);
db.Entry(instructorToUpdate).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
catch (DataException)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
}
PopulateAssignedCourseData(instructorToUpdate);
return View(instructorToUpdate);
} private void UpdateInstructorCourses(string[] selectedCourses, Instructor instructorToUpdate)
{
if (selectedCourses == null)
{
instructorToUpdate.Courses = new List<Course>();
return;
}
var selectedCoursesHS = new HashSet<string>(selectedCourses);
var instructorCourses = new HashSet<int>
(instructorToUpdate.Courses.Select(c => c.CourseID));
foreach (var course in db.Courses)
{
if (selectedCoursesHS.Contains(course.CourseID.ToString()))
{
if (!instructorCourses.Contains(course.CourseID))
{
instructorToUpdate.Courses.Add(course);
}
}
else
{
if (instructorCourses.Contains(course.CourseID))
{
instructorToUpdate.Courses.Remove(course);
}
}
}
} public ActionResult Delete(int id) // GET: /Instructor/Delete/5
{
Instructor instructor = db.Instructors.Find(id);
return View(instructor);
} [HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id) // POST: /Instructor/Delete/5
{
Instructor instructor = db.Instructors.Find(id);
db.Instructors.Remove(instructor);
db.SaveChanges();
return RedirectToAction("Index");
} protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
三、视图
Instructors:
@model ContosoUniversity.ViewModels.InstructorIndexData
@{ ViewBag.Title = "Instructors"; }
<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>
@foreach (var item in Model.Instructors)
{
string selectedRow = "";
if (item.PersonID == ViewBag.PersonID)
{ selectedRow = "selectedrow"; }
<tr class="@selectedRow" valign="top">
<td>@Html.ActionLink("Select", "Index", new { id = item.PersonID })
| @Html.ActionLink("Edit", "Edit", new { id = item.PersonID })
| @Html.ActionLink("Details", "Details", new { id = item.PersonID })
| @Html.ActionLink("Delete", "Delete", new { id = item.PersonID }) </td>
<td>@item.LastName </td>
<td>@item.FirstMidName </td>
<td>@String.Format("{0:d}", item.HireDate) </td>
<td>
@if (item.OfficeAssignment != null)
{ @item.OfficeAssignment.Location }
</td>
<td>
@{ foreach (var course in item.Courses)
{ @course.CourseID @: @course.Title <br />
} }
</td>
</tr>
}
</table>
@if (Model.Courses != null)
{
<h3>
Courses Taught by Selected Instructor</h3>
<table>
<tr> <th></th><th>ID</th> <th>Title</th> <th>Department</th> </tr>
@foreach (var item in Model.Courses)
{
string selectedRow = "";
if (item.CourseID == ViewBag.CourseID)
{ selectedRow = "selectedrow"; }
<tr class="@selectedRow">
<td>@Html.ActionLink("Select", "Index", new { courseID = item.CourseID }) </td>
<td>@item.CourseID </td>
<td>@item.Title </td>
<td>@item.Department.Name </td>
</tr>
}
</table>
}
@if (Model.Enrollments != null)
{
<h3> Students Enrolled in Selected Course</h3>
<table>
<tr> <th>Name</th><th>Grade</th></tr>
@foreach (var item in Model.Enrollments)
{
<tr>
<td>@item.Student.FullName </td>
<td>@Html.DisplayFor(modelItem => item.Grade) </td>
</tr>
}
</table>
}
Edit:
@model ContosoUniversity.Models.Instructor
@{ ViewBag.Title = "Edit";}
<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(model => model.PersonID)
<div class="editor-label"> @Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field"> @Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.FirstMidName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FirstMidName)
@Html.ValidationMessageFor(model => model.FirstMidName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.HireDate)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.HireDate)
@Html.ValidationMessageFor(model => model.HireDate)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.OfficeAssignment.Location)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.OfficeAssignment.Location)
@Html.ValidationMessageFor(model => model.OfficeAssignment.Location)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.OfficeAssignment.Location)
</div>
<div class="editor-field">
<table style="width: 100%">
<tr>
@{
int cnt = ;
List<ContosoUniversity.ViewModels.AssignedCourseData> courses = ViewBag.Courses;
foreach (var course in courses) {
if (cnt++ % == ) {
@: </tr> <tr>
}
@: <td>
<input type="checkbox"
name="selectedCourses"
value="@course.CourseID"
@(Html.Raw(course.Assigned ? "checked=\"checked\"" : "")) />
@course.CourseID @: @course.Title
@:</td>
}
@: </tr>
}
</table>
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>



MVC与EF结合:Contoso大学的更多相关文章
- Contoso 大学 - 1 - 为 ASP.NET MVC 应用程序创建 EF 数据模型
原文 Contoso 大学 - 1 - 为 ASP.NET MVC 应用程序创建 EF 数据模型 原文地址:Creating an Entity Framework Data Model for an ...
- Contoso 大学 - 使用 EF Code First 创建 MVC 应用
原文 Contoso 大学 - 使用 EF Code First 创建 MVC 应用 Contoso 大学 Web 示例应用演示了如何使用 EF 技术创建 ASP.NET MVC 应用.示例中的 Co ...
- Contoso 大学 - 使用 EF Code First 创建 MVC 应用,实例演练
Contoso 大学 Web 示例应用演示了如何使用 EF 技术创建 ASP.NET MVC 应用.示例中的 Contoso 大学是虚构的.应用包括了类似学生注册.课程创建以及教师分配等功能. 这个系 ...
- Contoso 大学 - 10 - 高级 EF 应用场景
原文 Contoso 大学 - 10 - 高级 EF 应用场景 By Tom Dykstra, Tom Dykstra is a Senior Programming Writer on Micros ...
- Contoso 大学 - 9 - 实现仓储和工作单元模式
原文 Contoso 大学 - 9 - 实现仓储和工作单元模式 By Tom Dykstra, Tom Dykstra is a Senior Programming Writer on Micros ...
- Contoso 大学 - 8 – 实现继承
原文 Contoso 大学 - 8 – 实现继承 By Tom Dykstra, Tom Dykstra is a Senior Programming Writer on Microsoft's W ...
- Contoso 大学 - 7 – 处理并发
原文 Contoso 大学 - 7 – 处理并发 By Tom Dykstra, Tom Dykstra is a Senior Programming Writer on Microsoft's W ...
- Contoso 大学 - 6 – 更新关联数据
原文 Contoso 大学 - 6 – 更新关联数据 By Tom Dykstra, Tom Dykstra is a Senior Programming Writer on Microsoft's ...
- Contoso 大学 - 5 – 读取关联数据
原文 Contoso 大学 - 5 – 读取关联数据 By Tom Dykstra, Tom Dykstra is a Senior Programming Writer on Microsoft's ...
- Contoso 大学 - 4 - 创建更加复杂的数据模型
原文 Contoso 大学 - 4 - 创建更加复杂的数据模型 原文地址:http://www.asp.net/mvc/tutorials/getting-started-with-ef-using- ...
随机推荐
- 虹软人脸识别在 linux中so文件加载不到的问题
其实是可以加载到的,不过是so文件放的位置不一对,最简单的方式是放在 /usr/lib64 目录下,也可自己设置. so文件加载不到会报这个错误: .lang.UnsatisfiedLinkEr ...
- UTF-8编码
UTF-8是UNICODE的一种变长度的编码表达方式<一般UNICODE为双字节(指UCS2)>,它由Ken Thompson于1992年创建,现在已经标准化为RFC 3629.UTF-8 ...
- DDD学习笔记(一)
最近开始筹备一个电商项目. 其实是公司的老本行了. 但今年公司希望在做项目的同时, 沉淀出一套针对电商的基础产品. 这样可以提高新项目的开发效率, 减少重复劳动. 那现如今, DDD(领域驱动设计)应 ...
- Rest架构下的增删改查
首先还是要连接一下什么是Rest, REST是英文representational state transfer(表象性状态转变)或者表述性状态转移;Rest是web服务的一种架构风格;使用HTTP, ...
- xsl 和xml transform方法的调用
xsl 和xml生成html,兼容多个浏览器 <html> <head> <meta charset="UTF-8"/> </head&g ...
- JAVA获取5位随机数
package baofoo.utils; import org.junit.Test; import java.text.SimpleDateFormat; import java.util.Dat ...
- hdu 4193 Non-negative Partial Sums 单调队列。
Non-negative Partial Sums Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 65536/32768 K (Jav ...
- Spring部分面试知识
对Spring的理解 spring是一个轻量级的开源框架,贯穿持久层.业务逻辑层.控制层.让每一个功能模块都可以独立的分开,降低耦合度,提高代码复用度.spring通过控制反转降低耦合性,一个对象的依 ...
- react context toggleButton demo
//toggleButton demo: //code: //1.Appb.js: import React from 'react'; import {ThemeContext, themes} f ...
- ThreeJS文字作为纹理贴图
文字作为纹理贴图 From:http://www.linhongxu.com/post/view?id=222 这里可以使用canvas作为纹理贴图,Three为我们提供里CanvasTexture ...