標籤:
首先配置web.config
<connectionStrings> <add name="BookDbContext" connectionString=" Data Source=.\SQLEXPRESS;Initial Catalog=sales;Persist Security Info=True;Integrated Security=SSPI;" providerName="System.Data.SqlClient" /> </connectionStrings>
然後在Model裡加入一個Book 類和一個BookDbContext類
Book類
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace MvcApplication3.Models{ public class Book { public int BookID { get; set; } public string BookName { get; set; } public string Author { get; set; } public string Publisher { get; set; } public decimal Price { get; set; } public string Remark { get; set; } }}
BookDbContext類
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Data.Entity;namespace MvcApplication3.Models{ /// <summary> /// BookDbContext代表EF中Book在資料庫中的內容物件,通過DbSet<Book>使實體類與資料庫關聯起來。Books屬性工作表示資料庫中的資料集實體,用來處理資料的存取與更新。BookDbContext派生自DbContext,須要加入System.Data.Entity的引用。 /// </summary> public class BookDbContext:DbContext { /// <summary> /// 表示用於運行建立、讀取、更新和刪除操作的類型化實體集。DbSet 不是公用可構造的。僅僅能從 System.Data.Entity.DbContext執行個體建立。 /// </summary> public DbSet<Book> Books { get; set; } }}
加入一個Book控制器
要瞭解FormCollection請參考:FormCollection傳值
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using MvcApplication3.Models;namespace MvcApplication3.Controllers{ public class BookController : Controller { // // GET: /Book/ BookDbContext db = new BookDbContext(); /// <summary> /// //查詢出全部的Book對象,組成一個Books,讓它展示在頁面首頁 /// </summary> /// <returns></returns> public ActionResult Index() { //這是一個簡單的Linq查詢,在對資料庫進行操作時。EF會檢查當前的資料連線指定的資料庫是否被建立,假設沒有則有EF負責依據實體模型類建立資料庫、資料表;假設存在,EF會將查詢條件加入到Sql查詢語句,再將Sql語句發送到資料庫進行資料讀取。在完畢資料讀取後,將資料轉換為實體物件集合。EF對資料庫的操作大致如此 var books = from b in db.Books select b; return View(books.ToList()); } [HttpGet] public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(Book book) { //MVC驗證中全部屬性驗證成功ModelState.IsValid等於true,僅僅要有一個驗證不成功ModelState.IsValid就等於false 所以我們能夠通過該屬性來推斷資料的有效性,但有時在資料驗證時有時我們不須要驗證全部的資料,比方登入時僅僅須要驗證username及password格式是否輸入正確就可以。使用下面方法能夠排除要驗證的欄位:ModelState.Remove("Email");不驗證Email。這樣Email這個欄位就不會被驗證了,Email驗證不通過ModelState.IsValid的值仍然是true if (ModelState.IsValid) { db.Books.Add(book); db.SaveChanges(); return RedirectToAction("Index"); } else { return View(book); } } [HttpGet] public ActionResult Delete(int id) { var data = from DataItem in db.Books where DataItem.BookID == id select DataItem; ViewData.Model = data.Single(); return View(); } [HttpPost] public ActionResult Delete(int id, FormCollection c) //事實上這的FormCollection c 換成 int a=5 或者 int a=6 都是能夠的。僅僅要保證這個Delete方法與上面的Delete方法參數不同就能夠了。
事實上也就是保證兩個方法構成重載 { //Find()是返回滿足條件的第一個元素,假設沒有該元素,則返回null。
Book book = db.Books.Find(id); //也能夠寫成:Book book=db.Books.FirstOrDefault(d=>d.BookID==id) db.Books.Remove(book); db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult Edit(int id) { //var data = from dataitem in db.Books // where dataitem.BookID == id // select dataitem; //ViewData.Model = data.Single(); //return View(); //Find()是返回滿足條件的第一個元素(即:Books中 BookID的的值為id的Book),假設沒有該元素。則返回null。 Book book = db.Books.Find(id); if (book == null) { return RedirectToAction("Index"); } return View(book); } [HttpPost] public ActionResult Edit(Book newbook) { try { Book oldbook = db.Books.Find(newbook.BookID); //使用來自控制器的當前值提供者的值更新指定的模型執行個體 UpdateModel(oldbook); //將在此上下文中所做的全部更改儲存到基礎資料庫。
db.SaveChanges(); return RedirectToAction("Index"); } catch (Exception ex) { //AddModelError:將指定的錯誤訊息加入到與指定鍵關聯的模型狀態字典的錯誤集合中。 ModelState.AddModelError("", "改動失敗。請查看具體錯誤資訊" + ex.Message + ex.StackTrace); } return View(newbook); } public ActionResult Details(int id) { //Find()是返回滿足條件的第一個元素(即:Books中 BookID的的值為id的Book),假設沒有該元素,則返回null。 Book book = db.Books.Find(id); if (book == null) { return RedirectToAction("Index"); } return View(book); } }}
view
Index 視圖 首頁
@model IEnumerable<MvcApplication3.Models.Book>@{ ViewBag.Title = "圖書列表-MvcBook";}<h2> 圖書列表</h2><p> @Html.ActionLink("添加圖書", "Create")</p><table> <tr> <th>圖書名稱</th><th>作者</th><th>出版社</th><th>價格</th><th>備忘</th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.BookName) </td> <td> @Html.DisplayFor(modelItem => item.Author) </td> <td> @Html.DisplayFor(modelItem => item.Publisher) </td> <td> @Html.DisplayFor(modelItem => item.Price) </td> <td> @Html.DisplayFor(modelItem => item.Remark) </td> <td> @Html.ActionLink("編輯", "Edit", new { id = item.BookID }) | @Html.ActionLink("具體", "Details", new { id = item.BookID }) | @Html.ActionLink("刪除", "Delete", new { id = item.BookID }) </td> </tr> }</table>
Create
@model MvcApplication3.Models.Book@{ ViewBag.Title = "Create";}<h2>添加</h2>@using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>Book</legend> <div class="editor-label"> @Html.LabelFor(model => model.BookName) </div> <div class="editor-field"> @Html.EditorFor(model => model.BookName) @Html.ValidationMessageFor(model => model.BookName) </div> <div class="editor-label"> @Html.LabelFor(model => model.Author) </div> <div class="editor-field"> @Html.EditorFor(model => model.Author) @Html.ValidationMessageFor(model => model.Author) </div> <div class="editor-label"> @Html.LabelFor(model => model.Publisher) </div> <div class="editor-field"> @Html.EditorFor(model => model.Publisher) @Html.ValidationMessageFor(model => model.Publisher) </div> <div class="editor-label"> @Html.LabelFor(model => model.Price) </div> <div class="editor-field"> @Html.EditorFor(model => model.Price) @Html.ValidationMessageFor(model => model.Price) </div> <div class="editor-label"> @Html.LabelFor(model => model.Remark) </div> <div class="editor-field"> @Html.EditorFor(model => model.Remark) @Html.ValidationMessageFor(model => model.Remark) </div> <p> <input type="submit" value="添加" /> </p> </fieldset>}<div> @Html.ActionLink("跳轉到首頁", "Index")</div>@section Scripts { @Scripts.Render("~/bundles/jqueryval")}
Delete
@model MvcApplication3.Models.Book@{ ViewBag.Title = "Delete";}<h2>Delete</h2><h3>Are you sure you want to delete this?</h3><fieldset> <legend>Book</legend> <table> <tr><th>圖書名稱:</th><th>@Html.DisplayFor(model => model.BookName)</th></tr> <tr><th>作者:</th><th>@Html.DisplayFor(model => model.Author)</th></tr> <tr><th>出版社:</th><th>@Html.DisplayFor(model => model.Publisher)</th></tr> <tr><th>價格:</th><th>@Html.DisplayFor(model => model.Price)</th></tr> <tr><th>備忘</th><th>@Html.DisplayFor(model => model.Remark)</th></tr> </table></fieldset>@using (Html.BeginForm()) { <p> <input type="submit" value="刪除" /> | @Html.ActionLink("跳轉到首頁", "Index") </p>}
Edit
@model MvcApplication3.Models.Book@{ ViewBag.Title = "Edit";}<h2>編輯</h2>@using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>Book</legend> @Html.HiddenFor(model => model.BookID) <div class="editor-label"> @Html.LabelFor(model => model.BookName) </div> <div class="editor-field"> @Html.EditorFor(model => model.BookName) @Html.ValidationMessageFor(model => model.BookName) </div> <div class="editor-label"> @Html.LabelFor(model => model.Author) </div> <div class="editor-field"> @Html.EditorFor(model => model.Author) @Html.ValidationMessageFor(model => model.Author) </div> <div class="editor-label"> @Html.LabelFor(model => model.Publisher) </div> <div class="editor-field"> @Html.EditorFor(model => model.Publisher) @Html.ValidationMessageFor(model => model.Publisher) </div> <div class="editor-label"> @Html.LabelFor(model => model.Price) </div> <div class="editor-field"> @Html.EditorFor(model => model.Price) @Html.ValidationMessageFor(model => model.Price) </div> <div class="editor-label"> @Html.LabelFor(model => model.Remark) </div> <div class="editor-field"> @Html.EditorFor(model => model.Remark) @Html.ValidationMessageFor(model => model.Remark) </div> <p> <input type="submit" value="儲存" /> </p> </fieldset>}<div> @Html.ActionLink("跳轉到首頁", "Index")</div>@section Scripts { @Scripts.Render("~/bundles/jqueryval")}
Details
@model MvcApplication3.Models.Book@{ ViewBag.Title = "Details";}<h2>Details</h2><fieldset> <legend>Book</legend> <table> <tr><th>圖書名稱:</th><th>@Html.DisplayFor(model => model.BookName)</th></tr> <tr><th>作者:</th><th>@Html.DisplayFor(model => model.Author)</th></tr> <tr><th>出版社:</th><th>@Html.DisplayFor(model => model.Publisher)</th></tr> <tr><th>價格:</th><th>@Html.DisplayFor(model => model.Price)</th></tr> <tr><th>備忘</th><th>@Html.DisplayFor(model => model.Remark)</th></tr> </table></fieldset><p> @Html.ActionLink("編輯", "Edit", new { id=Model.BookID }) | @Html.ActionLink("跳轉到首頁", "Index")</p>
著作權聲明:本文博主原創文章。部落格,未經同意不得轉載。
MVC Code First (代碼優先)