中文教程

1、通过 MVC 5 使用 Entity Framework 6 Code First 入门

https://docs.microsoft.com/zh-cn/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

2、通过 MVC 4 使用 Entity Framework 5 Code First 入门

https://docs.microsoft.com/zh-cn/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/

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 @:&nbsp; @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 @:&nbsp; @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大学的更多相关文章

  1. Contoso 大学 - 1 - 为 ASP.NET MVC 应用程序创建 EF 数据模型

    原文 Contoso 大学 - 1 - 为 ASP.NET MVC 应用程序创建 EF 数据模型 原文地址:Creating an Entity Framework Data Model for an ...

  2. Contoso 大学 - 使用 EF Code First 创建 MVC 应用

    原文 Contoso 大学 - 使用 EF Code First 创建 MVC 应用 Contoso 大学 Web 示例应用演示了如何使用 EF 技术创建 ASP.NET MVC 应用.示例中的 Co ...

  3. Contoso 大学 - 使用 EF Code First 创建 MVC 应用,实例演练

    Contoso 大学 Web 示例应用演示了如何使用 EF 技术创建 ASP.NET MVC 应用.示例中的 Contoso 大学是虚构的.应用包括了类似学生注册.课程创建以及教师分配等功能. 这个系 ...

  4. Contoso 大学 - 10 - 高级 EF 应用场景

    原文 Contoso 大学 - 10 - 高级 EF 应用场景 By Tom Dykstra, Tom Dykstra is a Senior Programming Writer on Micros ...

  5. Contoso 大学 - 9 - 实现仓储和工作单元模式

    原文 Contoso 大学 - 9 - 实现仓储和工作单元模式 By Tom Dykstra, Tom Dykstra is a Senior Programming Writer on Micros ...

  6. Contoso 大学 - 8 – 实现继承

    原文 Contoso 大学 - 8 – 实现继承 By Tom Dykstra, Tom Dykstra is a Senior Programming Writer on Microsoft's W ...

  7. Contoso 大学 - 7 – 处理并发

    原文 Contoso 大学 - 7 – 处理并发 By Tom Dykstra, Tom Dykstra is a Senior Programming Writer on Microsoft's W ...

  8. Contoso 大学 - 6 – 更新关联数据

    原文 Contoso 大学 - 6 – 更新关联数据 By Tom Dykstra, Tom Dykstra is a Senior Programming Writer on Microsoft's ...

  9. Contoso 大学 - 5 – 读取关联数据

    原文 Contoso 大学 - 5 – 读取关联数据 By Tom Dykstra, Tom Dykstra is a Senior Programming Writer on Microsoft's ...

  10. Contoso 大学 - 4 - 创建更加复杂的数据模型

    原文 Contoso 大学 - 4 - 创建更加复杂的数据模型 原文地址:http://www.asp.net/mvc/tutorials/getting-started-with-ef-using- ...

随机推荐

  1. 分布式版本控制系统Git——使用GitStack+TortoiseGit 图形界面搭建Git环境(服务器端及客户端)(转)

    近期想改公司内部的源码管控从TFS为git,发现yubinfeng大侠有关git的超详细大作,现将其转载并记录下,以防忘记,其原博客中有更加详细的git及.net开发相关内容.原文地址:http:// ...

  2. 个人作业1——个人阅读&提问题

    第一部分:结缘计算机   上大学前接触了一些网游,如魔域.DNF等.偶然间朋友介绍了一些辅助软件,当时非常地好奇这些辅助软件是如何制作出来的,就上百度搜索了一些关键词,然后就了解到了易语言.VB.金山 ...

  3. 动态rem解决移动前端适配

    背景 移动前端适配一直困扰很多人,我自己也是从最初的媒体查询,到后来的百分比,再到padding-top这种奇巧淫技,再到css3新单位vw这种过渡转变 但这些都或多或少会有些问题,直到使用了动态re ...

  4. jquery对象与dom对象之间互相转换的方法

    本文主要讲述jquery对象和js里的dom对象之间互相转换的方法,使jquery对象可以直接使用js里的方法,或js里的dom对象使用jquery里的方法. jquery对象和dom对象是不一样的, ...

  5. Web开发 学习积累20161018

    项目 一.项目做的是什么 业务逻辑 -> 增删改查 二.什么是面向对象编程,它有哪些好处 oop:object oriented programming <>核心思想:使用人类思考问 ...

  6. Spring MVC 实现Excel的导入导出功能(2:Excel的导入优化和Excel的导出)

    Excel的导入V2优化版 有些时候文件上传这一步骤由前端来处理,只将上传后的 URL 传输给后端(可以参考上一文中的图片上传功能),也就是导入请求中并不会直接处理 MultipartFile 对象, ...

  7. 撩课-Web大前端每天5道面试题-Day5

    1.写一个深度克隆方法(es5)? /** * 深拷贝 * @param {object}fromObj 拷贝的对象 * @param {object}toObj 目标对象 */ function d ...

  8. 零基础学python习题 - 进入python的世界

    1. python拥有以下特性:面向对象的特性.动态性.内置的数据结构.简单性.健壮性.跨平台性.可扩展性.强类型语言.应用广泛 2. python 需要  编译 3. 以下不属于python内置数据 ...

  9. jQuery轮播图(二)利用构造函数和原型创建对象以实现继承

    本文是在我开始学习JavaScript继承时,对原型继承的一些理解和运用.文中所述的继承方式均是使用js特有的原型链方式,实际上有了ES6的类之后,实现继承的就变得十分简单了,所以这种写法现在也不在推 ...

  10. 什么是首字节时间(TTFB)

    第一字节响应时间(TTFB)=从发送请求到WEB服务器的时间+WEB服务器处理请求并生成响应花费的时间+WEB服务器生成响应到浏览器花费的时间测量第一字节响应时间(TTFB)的工具:http://ww ...