EF实现增删查改功能
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了EF实现增删查改功能相关的知识,希望对你有一定的参考价值。
In the previous tutorial you created an MVC application that stores and displays data using the Entity Framework and SQL Server LocalDB. In this tutorial you‘ll review and customize the CRUD (create, read, update, delete) code that the MVC scaffolding automatically creates for you in controllers and views.
在之前的课程中,你使用Ef和SQL Server LocalDB创建了可以存储和显示数据的MVC程序,在这个系列的课程中,你将会复习和自定义MVC增删查改的代码。
Note It‘s a common practice to implement the repository pattern in order to create an abstraction layer between your controller and the data access layer. To keep these tutorials simple and focused on teaching how to use the Entity Framework itself, they don‘t use repositories. For information about how to implement repositories, see the ASP.NET Data Access Content Map.
现在很普遍会实现仓储模式,用来在你的控制器和数据访问层之间,创建一个抽象层。为了保证这个系列的课程,尽可能的简单,并且集中注意力在教授怎么去使用EF,这里不使用仓储模式,要了解怎么实现仓储模式,请看链接的文章。
Create a Details Page
The scaffolded code for the Students Index
page left out the Enrollments
property, because that property holds a collection. In the Details
page you‘ll display the contents of the collection in an html table.
基架忽视了Student列表页的Enrollments属性,因为这个属性包含一个集合,在详细页面,你将会在一个HTML表格中显示这个集合的内容。
1 public ActionResult Details(int? id) 2 { 3 if (id == null) 4 { 5 return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 6 } 7 Student student = db.Students.Find(id); 8 if (student == null) 9 { 10 return HttpNotFound(); 11 } 12 return View(student); 13 }
After the EnrollmentDate
field and immediately before the closing </dl>
tag, add the highlighted code to display a list of enrollments, as shown in the following example: 在Enrollmentdate字段的后面,添加下面高亮显示的代码:
1 @model ContosoUniversity.Models.Student 2 3 @{ 4 ViewBag.Title = "Details"; 5 Layout = "~/Views/Shared/_Layout.cshtml"; 6 } 7 8 <h2>Details</h2> 9 10 <div> 11 <h4>Student</h4> 12 <hr /> 13 <dl class="dl-horizontal"> 14 <dt> 15 @Html.DisplayNameFor(model => model.LastName) 16 </dt> 17 18 <dd> 19 @Html.DisplayFor(model => model.LastName) 20 </dd> 21 22 <dt> 23 @Html.DisplayNameFor(model => model.FirstMidName) 24 </dt> 25 26 <dd> 27 @Html.DisplayFor(model => model.FirstMidName) 28 </dd> 29 30 <dt> 31 @Html.DisplayNameFor(model => model.EnrollmentDate) 32 </dt> 33 34 <dd> 35 @Html.DisplayFor(model => model.EnrollmentDate) 36 </dd> 37 <dt> 38 @Html.DisplayNameFor(model=>model.Enrollments) 39 </dt> 40 <dd> 41 <table> 42 <tr> 43 <th>Course Title</th> 44 <th>Grade</th> 45 </tr> 46 @foreach (var item in Model.Enrollments) 47 { 48 <td>@Html.DisplayFor(s=>item.Course.Title)</td> 49 <td>@Html.DisplayFor(s=>item.Grade)</td> 50 } 51 </table> 52 </dd> 53 54 </dl> 55 </div> 56 <p> 57 @Html.ActionLink("Edit", "Edit", new { id = Model.ID }) | 58 @Html.ActionLink("Back to List", "Index") 59 </p>
小技巧:Ctrl+K+D,代码缩进
现在,运行项目,点击详细列表:
Update the Create Page
In Controllers\StudentController.cs, replace the HttpPost
Create
action method with the following code to add a try-catch
block and remove ID
from the Bind attribute for the scaffolded method:
打开Student控制器,用下面的代码来更新:
1 // POST: Students/Create 2 // 为了防止“过多发布”攻击,请启用要绑定到的特定属性,有关 3 // 详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。 4 [HttpPost] 5 [ValidateAntiForgeryToken] 6 public ActionResult Create([Bind(Include = "LastName,FirstMidName,EnrollmentDate")] Student student) 7 { 8 try 9 { 10 if (ModelState.IsValid) 11 { 12 db.Students.Add(student); 13 db.SaveChanges(); 14 return RedirectToAction("Index"); 15 } 16 17 } 18 catch (DataException /*dex*/) 19 { 20 //Log the error (uncomment dex variable name and add a line here to write a log. 21 ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); 22 } 23 24 25 return View(student); 26 }
This code adds the Student
entity created by the ASP.NET MVC model binder to the Students
entity set and then saves the changes to the database. (Model binder refers to the ASP.NET MVC functionality that makes it easier for you to work with data submitted by a form; a model binder converts posted form values to CLR types and passes them to the action method in parameters. In this case, the model binder instantiates a Student
entity for you using property values from the Form
collection.)
You removed ID
from the Bind attribute because ID
is the primary key value which SQL Server will set automatically when the row is inserted. Input from the user does not set the ID
value.
Security Note: The ValidateAntiForgeryToken
attribute helps prevent cross-site request forgery attacks. It requires a corresponding Html.AntiForgeryToken()
statement in the view, which you‘ll see later.
ValidateAntiForgeryToken属性帮助阻止跨站点请求攻击,它需要在视图中写上Html.AntiForgeryToken()语句。你后面将会看到。
The Bind
attribute is one way to protect against over-posting in create scenarios. For example, suppose the Student
entity includes a Secret
property that you don‘t want this web page to set.
Even if you don‘t have a Secret
field on the web page, a hacker could use a tool such asfiddler, or write some javascript, to post a Secret
form value. Without the Bind attribute limiting the fields that the model binder uses when it creates a Student
instance, the model binder would pick up that Secret
form value and use it to create the Student
entity instance. Then whatever value the hacker specified for the Secret
form field would be updated in your database. The following image shows the fiddler tool adding theSecret
field (with the value "OverPost") to the posted form values. 这段话,简而言之就是,没有Bind属性,黑客就会将数据Post到你的数据库中。(PS:本来翻译好了,结果手残,按错了,懒得再翻译。)
You can prevent overposting in edit scenarios is by reading the entity from the database first and then calling TryUpdateModel
, passing in an explicit allowed properties list. That is the method used in these tutorials.
An alternative way to prevent overposting that is preferrred by many developers is to use view models rather than entity classes with model binding. Include only the properties you want to update in the view model. Once the MVC model binder has finished, copy the view model properties to the entity instance, optionally using a tool such as AutoMapper. Use db.Entry on the entity instance to set its state to Unchanged, and then set Property("PropertyName").IsModified to true on each entity property that is included in the view model. This method works in both edit and create scenarios.
(PS:这里我有空再完善了,先学完这个系列的课程)
Other than the Bind
attribute, the try-catch
block is the only change you‘ve made to the scaffolded code. If an exception that derives from DataException is caught while the changes are being saved, a generic error message is displayed. DataException exceptions are sometimes caused by something external to the application rather than a programming error, so the user is advised to try again. Although not implemented in this sample, a production quality application would log the exception. For more information, see the Log for insight section in Monitoring and Telemetry (Building Real-World Cloud Apps with Azure).
(PS:这里我有空再完善了,先学完这个系列的课程)
The code in Views\Student\Create.cshtml is similar to what you saw in Details.cshtml, except that EditorFor
and ValidationMessageFor
helpers are used for each field instead of DisplayFor
. Here is the relevant code:
(PS:这里我有空再完善了,先学完这个系列的课程)
Update the Edit HttpPost Method
In Controllers\StudentController.cs, the HttpGet
Edit
method (the one without the HttpPost
attribute) uses theFind
method to retrieve the selected Student
entity, as you saw in the Details
method. You don‘t need to change this method.
However, replace the HttpPost
Edit
action method with the following code:
1 [HttpPost,ActionName("Edit")] 2 [ValidateAntiForgeryToken] 3 public ActionResult EditPost(int?id) 4 { 5 if (id == null) 6 { 7 return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 8 } 9 var studentTOUpdate = db.Students.Find(id); 10 if (TryUpdateModel(studentTOUpdate, "", new string[] {"LastName","FirstName","EnrollmentDate" })) 11 { 12 13 try 14 { 15 db.SaveChanges(); 16 return RedirectToAction("Index"); 17 } 18 catch (DataException /*dex */) 19 { 20 ModelState.AddModelError("", "不能保存,请再试"); 21 } 22 } 23 return View(studentTOUpdate); 24 }
These changes implement a security best practice to prevent overposting, The scaffolder generated a Bind
attribute and added the entity created by the model binder to the entity set with a Modified flag. That code is no longer recommended because the Bind
attribute clears out any pre-existing data in fields not listed in the Include
parameter. In the future, the MVC controller scaffolder will be updated so that it doesn‘t generate Bind
attributes for Edit methods.
The new code reads the existing entity and calls TryUpdateModel to update fields from user input in the posted form data. The Entity Framework‘s automatic change tracking sets the Modified flag on the entity. When the SaveChangesmethod is called, the Modified
flag causes the Entity Framework to create SQL statements to update the database row. Concurrency conflicts are ignored, and all columns of the database row are updated, including those that the user didn‘t change. (A later tutorial shows how to handle concurrency conflicts, and if you only want individual fields to be updated in the database, you can set the entity to Unchanged and set individual fields to Modified.)
以上是关于EF实现增删查改功能的主要内容,如果未能解决你的问题,请参考以下文章