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 Studententity 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 Studententity 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 EditorForand 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 Includeparameter. 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.)

时间: 2024-10-27 13:15:15

EF实现增删查改功能的相关文章

实现基本的增删查改功能

1. 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 scaffol

EAS开发之对已有单据的增删查改功能开发

一:对于一个已经在其他业务部门定义好的业务单元,在另一个部门新增该业务单元的增删查改操作,应该怎么做? 由于业务单元已经定义过了,所以我们不能再进行建模.定义单据ui.而是要开发出一个单据列表展示界面以及操作功能. 二:界面开发 在当前业务部门的业务组的元数据的client目录下,新建--用户界面--继承CoreUI,完成.得到一个空白的frame. 然后,从右侧控件窗口中选择控件,拖动容器.组件等进行页面搭建. 界面搭建完成后,发布. 三:界面代码逻辑 界面发布后会在代码目录下生成相应的ui.

SQL基础教程--实现增删查改功能(W3School)

1.SQL DML 和 DDL 可以把 SQL 分为两个部分:数据操作语言 (DML) 和 数据定义语言 (DDL). SQL (结构化查询语言)是用于执行查询的语法.但是 SQL 语言也包含用于更新.插入和删除记录的语法. 查询和更新指令构成了 SQL 的 DML 部分: SELECT - 从数据库表中获取数据 UPDATE - 更新数据库表中的数据 DELETE - 从数据库表中删除数据 INSERT INTO - 向数据库表中插入数据 SQL 的数据定义语言 (DDL) 部分使我们有能力创

MVC 强类型传值Model。和弱类型传值ViewData[&amp;quot;&amp;quot;]。及用EF进行增删查改(母版页的使用)

<1> 控制器 </pre><pre name="code" class="csharp">using MvcTest.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcTest.Controllers { public cla

.NET mvc+EF+EasyUI增删查改

链接:https://pan.baidu.com/s/1ZGFieFO-D7_hvtFy5xro5w 提取码:t1yw 复制这段内容后打开百度网盘手机App,操作更方便哦 原文地址:https://www.cnblogs.com/fzqm-lwz/p/10548865.html

Entity FrameWork 增删查改的本质

之前的文章里面已经说了,EF的增删查改.那时候的修改,删除,只能是先查询出来要修改的数据,再修改,删除...现在来一个改进版的,增删查改. 1.Add 1 static void Add() 2 { 3 //1.创建student对象,并使用对象初始化器,初始化这个对象 4 Studnet stu = new Studnet() 5 { 6 s_Name = "古巨基", 7 s_Sex = "男", 8 s_Age = 39, 9 c_ID = 2, 10 11

golang使用json格式实现增删查改

需求和思路 在一般的小项目或者一个小软件,例如客户端之类的小程序中,可能会需要数据的持久化.但是使用一般的数据库(Mysql)之类的不合适.使用sqlite3这种嵌入式的是个较好的方法,但是Go语言中sqlite3的库是C语言的,Cgo不支持跨平台编译.正是由于这种需求,才想到使用json格式将数据直接保存在文件中. 具体的思路是怎么样呢? 在Go语言中如果要将数据转化成json格式的话,有两种格式 struct 和 map. 如果同时需要增删查改功能的话,将map作为中间格式是比较合适的.接下

EF增删查改加执行存储过程和sql语句,多种方法汇总

1 ActionUrl c = new ActionUrl() { ActionName="test", RequestUrl="/123/123", SubTime=DateTime.Now }; 2 //增 3 using (EntityContext db = new EntityContext()) 4 { 5 6 /*方法1*/ 7 db.ActionUrls.Add(c); 8 db.SaveChanges(); 9 /*方法2*/ 10 db.Set&

在MVC程序中,使用泛型仓储模式和工作单元实现增删查改

在这片文章中,我将自己动手为所有的实体:写一个泛型仓储类,还有一个工作单元. 工作单元的职责就是:为每一个实体,创建仓储实例.仓储(仓库)的职责:增删查改的功能实现. 我们将会在控制器中,创建工作单元类(UnitOfWork)的实例,然后根据实体,创建仓储实例,再就是使用仓储里面的方法,做操作了. 下面的图中,解释了,仓储和EF 数据上文的关系,在这个图里面,MVC控制器和仓储之间的交互,是通过工作单元来进行的,而不是直接和EF接触. 那么你可能就要问了,为什么要使用工作单元??? 工作单元,就