EF實現增刪查改功能

来源:http://www.cnblogs.com/caofangsheng/archive/2016/03/17/4606172.html
-Advertisement-
Play Games

In the previous tutorial you created an MVC application that stores and displays data using the Entity Framework and SQL Server LocalDB. In this tutor


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.)

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 系統來自系統媽:http://www.xitongma.com 電腦公司最新GHOST win7系統32位優化精簡版V2016年3月 系統概述 電腦公司ghost win7 x86(32位)萬能裝機版集成的軟體符合電腦公司及電腦城裝機絕大多數人要求及喜好,既大眾,又時尚,人人喜歡,處處適用。自動判斷
  • asp.net 編譯錯誤類型“同時存在於”不同的dll中. 出現這種錯誤大概有三種情況: 1、ASPX頁面,一個*.ASPX,對應著一個*.cs文件,兩者其實是一個文件,通過兩者實現代碼分離,每個*.aspx頁面都引用著自身的CS文件:如果兩個頁面引用了相同得.CS文件,在發佈得時候也會出現這種錯誤
  • 普通電腦沒有通用的輸入輸出口(GPIO),但有時候我就想輸入一個開關量。 比如讓用戶拉一下拉繩開關就啟動某個應用,比如裝一個觸點開關判斷門是打開的還是關閉的,比如.... 需求是如此簡單,你都不願意花幾十塊錢去買一個單片機,更不用說PCI擴展卡、PLC之類的了。。怎麼辦吶? 有辦法!最簡單的用串口就
  • 運行-cmd,輸入下麵命令:C:\WINDOWS\Microsoft.NET\Framework\v版本號\aspnet_regiis.exe -i即可 以下是aspnet_regiis.exe參數的說明信息: -i - 安裝 ASP.NET 的此版本,並更新 IIS 元資料庫根處的腳本映射和根以下
  • 使用ASP.NET模版生成HTML靜態頁面並不是難事,主要是使各個靜態頁面間的關聯和鏈接如何保持完整。本文介紹了使用ASP.NET模版生成HTML靜態頁面的五種方案。 ASP.NET模版生成HTML靜態頁面方案1: 你可以用這個函數獲取網頁的客戶端的html代碼,然後保存到.html文件里就可以了。
  • 泛型是CLR和編程語言提供的一種特殊機制,它用於滿足“演算法重用” 。 可以想象一下一個只有操作的參數的數據類型不同的策略模式,完全可以用泛型來化為一個函數。 以下是它的優勢: 這就是為什麼List<T>淘汰了ArrayList的原因,特別是在進行值類型操作時,因為裝箱拆箱過多而差距很大。 約定:泛型
  • 本篇體驗ASP.NET Web API的安全管道。這裡的安全管道是指在請求和響應過程中所經歷的各個組件或進程,比如有IIS,HttpModule,OWIN,WebAPI,等等。在這個管道中大致分兩個階段,一個是驗證階段,另一個是授權階段。在ASP.NET Web API v1版本的時候,安全管道大致
  • 1. 【二進位(0~1)、八進位(0~7)、十進位(0~9)】→十六進位(0~15,10~15→A~F) 101011→1*20+1*21+0*22+1*23+0*24+1*25=1+2+0+8+0+32=43 053→3*80+5*81=3+40=43 0x2B=B*160+2*161=11+32
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...