中文教程

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. 微信授权错误:"errcode":40163,"errmsg":"codebeenused

    微信网页授权获取code值回调两次的问题 1.说是域名原因,目前未测试,没有正确的域名 问题描述:在调用微信网页授权获取openid值时,先获取的code值,但是code值的接口 会走两次回调.而co ...

  2. WPF月视图控件

    简介 在做一个应用时,需要做成日历月视图的形式.自己做较麻烦,于是上网找找看,在CodeProject上发现了这个Quick and Simple WPF Month-view Calendar,可是 ...

  3. 使用dom4j写xml文件——源码

    1 dom4j下载与配置 1.1 dom4j下载 请移步下载链接 1.2 maven依赖 <dependency> <groupId>org.dom4j</groupId ...

  4. jdk锁相关

    锁类型 可重入锁:在执行对象中所有同步方法不用再次获得锁 可中断锁:在等待获取锁过程中可中断 公平锁: 按等待获取锁的线程的等待时间进行获取,等待时间长的具有优先获取锁权利 读写锁:对资源读取和写入的 ...

  5. MySQL并发控制

    并发即指在同一时刻,多个操作并行执行.MySQL对并发的处理主要应用了两种机制——是“锁”和“多版本控制”. 锁 锁分为读锁和写锁两种,也称作共享锁和排他锁.因为多个读操作同时进行是不会破坏数据的,所 ...

  6. equals、==和hashCode

    equals和== ==可以用于基本类型和引用类型:当用于基本类型时,比较值是否相同:当用于引用类型时,比较的是所指向的对象的地址是否相同.如果有包装类型,则先将包装类型转换为基本类型再比较值是否相等 ...

  7. 几个css3动画库

    Hover.css 查看演示: http://ianlunn.github.io/Hover/ github地址: https://github.com/IanLunn/Hover Animate.c ...

  8. POJ P2828 Buy Ticket——线段树的其他信息维护

    Description Railway tickets were difficult to buy around the Lunar New Year in China, so we must get ...

  9. POJ P1741 Tree 解题报告

    Description Give a tree with n vertices,each edge has a length(positive integer less than 1001). Def ...

  10. JavaWeb学习总结(二):Http协议

    一.什么是HTTP协议 HTTP是hypertext transfer protocol(超文本传输协议)的简写,它是TCP/IP协议的一个应用层协议,用于定义WEB浏览器与WEB服务器之间交换数据的 ...