添加Model和添加普通类的操作是一样的,默认的约定是将它放在Models文件夹中。我们在Models文件夹上面点击右键,选择“添加”>“类”,在打开的对话框中输入类名“Book”,点击“添加”按钮。编辑器会为我们打开Book类,我们对这个类进行如下修改:
using System; namespace MvcHelloworld.Models { publicclass Book { publicint BookID { get; set; } publicstring BookName { get; set; } publicstring Author { get; set; } publicstring Publisher { get; set; } publicdecimal Price { get; set; } publicstring Remark { get; set; } } }
我们将使用这个类来表示数据库中的记录。每一个Book类的实例对应数据库中的一行,Book类中的每一个属性被映射到数据库中的一列。
using System; using System.Data.Entity; namespace MvcHelloworld.Models { publicclass BookDbContext : DbContext { public DbSet<Book> Books { get; set; } } }
BookDbContext代表EF中Book在数据库中的上下文对象,通过DbSet<Book>使实体类与数据库关联起来。Books属性表示数据库中的数据集实体,用来处理数据的存取与更新。BookDbContext派生自DbContext,需要添加System.Data.Entity的引用。
<connectionStrings> <add name="BookDbContext" connectionString=" Data Source=.\SQLEXPRESS;Initial Catalog=db_book;Persist Security Info=True;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/> </connectionStrings>
我们将数据库连接的name属性设置为“BookDbContext”,这个连接会被BookDbContext类使用,并根据连接创建相应的数据库。
public ActionResult Index() { var books = from bin db.Books where b.Author=="Tom" select b; return View(books.ToList()); }
@model IEnumerable<MvcHelloworld.Models.Book> @{ ViewBag.Title = "图书列表 - MvcBook"; } <h2>图书列表</h2> <p> @Html.ActionLink("增加图书", "Create") </p> <table> <tr> <th> 图书名称 </th> <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>
编译并运行程序,在浏览器中输入地址:http://localhost:xxx/Book,得到的运行结果如下:
@model MvcHelloworld.Models.Book @{ ViewBag.Title = "新增图书 - MvcBook"; } <h2>新增图书</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>图书</legend> <div class="editor-label"> 图书名称 </div> <div class="editor-field"> @Html.EditorFor(model => model.BookName) @Html.ValidationMessageFor(model => model.BookName) </div> <div class="editor-label"> 作者 </div> <div class="editor-field"> @Html.EditorFor(model => model.Author) @Html.ValidationMessageFor(model => model.Author) </div> <div class="editor-label"> 出版社 </div> <div class="editor-field"> @Html.EditorFor(model => model.Publisher) @Html.ValidationMessageFor(model => model.Publisher) </div> <div class="editor-label"> 价格 </div> <div class="editor-field"> @Html.EditorFor(model => model.Price) @Html.ValidationMessageFor(model => model.Price) </div> <div class="editor-label"> 备注 </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("Back to List", "Index") </div>
分析这段代码:
[HttpPost] public ActionResult Create(Book book) { if (ModelState.IsValid) { db.Books.Add(book); db.SaveChanges(); return RedirectToAction("Index"); } else return View(book); }
这时,我们在页面上输入数据,并点击“增加”按钮时,EF就会通过这段代码来添加一行数据库记录。打开数据库,我们可以看到如下记录:
publicclass Book { publicint BookID { get; set; } [Required(ErrorMessage="必须输入图书名称")] [StringLength(maximumLength:100, MinimumLength=1, ErrorMessage="最多允许输入100个字符")] publicstring BookName { get; set; } [Required(ErrorMessage ="必须输入作者名称")] publicstring Author { get; set; } [Required(ErrorMessage ="必须输入出版社")] publicstring Publisher { get; set; } publicdecimal Price { get; set; } publicstring Remark { get; set; } }
将数据库中之前生成的数据库db_Book删除掉,重新生成解决方案,打开新增页面,不输入任何数据的时候点击“增加”按钮,这个时侯,界面上会出现一些提示信息,并且阻止了我们进行数据的提交操作。界面如下:
BookController代码 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcHelloworld.Models; namespace MvcHelloworld.Controllers { publicclass BookController : Controller { BookDbContext db =new BookDbContext(); public ActionResult Index() { var books = from b in db.Books select b; return View(books.ToList()); } public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(Book book) { if (ModelState.IsValid) { db.Books.Add(book); db.SaveChanges(); return RedirectToAction("Index"); } else return View(book); } public ActionResult Edit(int id) { 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("Details", new { id = newBook.BookID }); } catch (Exception ex) { ModelState.AddModelError("", "修改失败,请查看详细错误信息:"+ ex.Message); } return View(newBook); } public ActionResult Details(int id) { Book book = db.Books.Find(id); if (book ==null) return RedirectToAction("Index"); return View(book); } public ActionResult Delete(int id) { Book book = db.Books.Find(id); if (book ==null) return RedirectToAction("Index"); return View(book); } [HttpPost] public ActionResult Delete(int id, FormCollection collection) { Book book = db.Books.Find(id); db.Books.Remove(book); db.SaveChanges(); return RedirectToAction("Index"); } } }