或者:http://www.codeproject.com/Articles/640302/CRUD-Operations-Using-Entity-Framework-Code-Fi
系列目錄:
- Relationship in Entity Framework Using Code First Approach With Fluent API【【使用EF Code-First方式和Fluent API來探討EF中的關系】】
- Code First Migrations with Entity Framework【使用EF 做數據庫遷移】
- CRUD Operations Using Entity Framework 5.0 Code First Approach in MVC【在MVC中使用EF 5.0做增刪查改】
- CRUD Operations Using the Repository Pattern in MVC【在MVC中使用倉儲模式,來做增刪查改】
- CRUD Operations Using the Generic Repository Pattern and Unit of Work in MVC【在MVC中使用泛型倉儲模式和工作單元來做增刪查改】
- CRUD Operations Using the Generic Repository Pattern and Dependency Injection in MVC【在MVC中使用泛型倉儲模式和依賴注入,來做增刪查改】
本來不想寫這篇的,因為感覺增刪查改,實在是太Easy了。好了,為了鞏固學習,還是繼續吧:
打算實現書籍的增刪查改,有兩個實體,一個是Book【書籍實體】,另外一個是出版商實體【Publisher】,一個出版商可以出版很多書籍,一本書只能是由一個出版商出版。所以,書籍和出版商之間是一對多的關系。
先來看看整個項目的結構吧:

Entity實體中:
BaseEntity實體:【日期使用了數據注解,這樣在顯示的時候,就有格式了。】
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EF.Entity { public abstract class BaseEntity { /// <summary>
/// ID /// </summary>
public int ID { get; set; } /// <summary>
/// 添加時間 /// </summary>
///
[DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime AddedDate { get; set; } /// <summary>
/// 修改時間 /// </summary>
///
[DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime ModifiedDate { get; set; } } }
Book實體:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EF.Entity { /// <summary>
/// Book實體 /// </summary>
public class Book:BaseEntity { /// <summary>
/// 書名 /// </summary>
public string BookName { get; set; } /// <summary>
/// 書的作者 /// </summary>
public string BookAuthor { get; set; } /// <summary>
/// 書的價格 /// </summary>
public decimal BookPrice { get; set; } /// <summary>
/// 出版商編號 /// </summary>
public int PublisherId { get; set; } /// <summary>
/// 導航屬性---出版商 /// </summary>
public virtual Publisher Publisher { get; set; } } }
出版商實體:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace EF.Entity { public class Publisher:BaseEntity { /// <summary>
/// 出版商的名字 /// </summary>
public string PublisherName { get; set; } /// <summary>
/// 導航屬性 /// </summary>
public virtual ICollection<Book> Books { get; set; } } }
然后在EF.Data項目中:
BookMap類:
using EF.Entity; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EF.Data { public class BookMap:EntityTypeConfiguration<Book> { public BookMap() { //配置主鍵
this.HasKey(s => s.ID); //配置字段
this.Property(s => s.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); this.Property(s => s.BookName).HasColumnType("nvarchar").HasMaxLength(50).IsRequired(); // this.Property(s => s.BookAuthor).HasColumnType("nvarchar(50)").IsRequired();//注意這個和BookName字段配置的區別之處:這樣寫EF生成不了數據庫
this.Property(s => s.BookAuthor).HasColumnType("nvarchar").HasMaxLength(50).IsRequired(); this.Property(s => s.BookPrice).IsRequired(); this.Property(s => s.AddedDate).IsRequired(); this.Property(s => s.ModifiedDate).IsRequired(); this.Property(s => s.PublisherId).IsRequired(); //配置關系[一個出版商可以出版很多書籍]【外鍵單獨配置,不是必須在Property中配置,當然也可以在Property中配置】
this.HasRequired(s => s.Publisher).WithMany(s => s.Books).HasForeignKey(s => s.PublisherId).WillCascadeOnDelete(true); //配置表名字
this.ToTable("Books"); } } }
PublisherMap類:
using EF.Entity; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EF.Data { public class PublisherMap:EntityTypeConfiguration<Publisher> { public PublisherMap() { //配置主鍵
this.HasKey(s => s.ID); this.Property(s => s.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); // this.Property(s => s.PublisherName).HasColumnType("nvarchar(50)").IsRequired();//這樣寫,有問題,生成不了數據庫
this.Property(s => s.PublisherName).HasColumnType("nvarchar").HasMaxLength(50).IsRequired(); this.Property(s => s.AddedDate).IsRequired(); this.Property(s => s.ModifiedDate).IsRequired(); } } }
出版商我這里不做增刪查改,到時候手動添加幾條數據進去,然后在Book的視圖中,把出版商做成下拉框的樣式:所以我這里額外添加一個實體:【PublisherModel實體中的構造函數里的初始化屬性嗲嗎,不能忘記!!!】
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; namespace EF.Web.Models { public class PublisherModel { public PublisherModel() { PublisherList = new List<SelectListItem>(); } [Display(Name="PublisherName")] public int PublisherID { get; set; } public List<SelectListItem> PublisherList { get; set; } } }
數據上下文類:
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace EF.Data { public class EFDbContext:DbContext { public EFDbContext() : base("name=DbConnectionString") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { var typesToRegister = Assembly.GetExecutingAssembly().GetTypes() .Where(type => !String.IsNullOrEmpty(type.Namespace)) .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>)); foreach (var type in typesToRegister) { dynamic configurationInstance = Activator.CreateInstance(type); modelBuilder.Configurations.Add(configurationInstance); } //base.OnModelCreating(modelBuilder);
} } }
Ef.Data項目和Web項目中都要加上連接字符串:
<connectionStrings>
<add name="DbConnectionString" connectionString="Server=.;Database=EFCURDDB;uid=sa;Pwd=Password_1" providerName="System.Data.SqlClient"/>
</connectionStrings>
現在看看Web項目:
using EF.Data; using EF.Entity; using EF.Web.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Mvc; namespace EF.Web.Controllers { public class BookController : Controller { private EFDbContext db; public BookController() { db = new EFDbContext(); } #region 列表
/// <summary>
/// 列表 /// </summary>
/// <returns></returns>
public ActionResult Index() { return View(db.Set<Book>().ToList()); } #endregion
#region AddBook
/// <summary>
/// 添加Book /// </summary>
/// <returns></returns>
public ActionResult AddBook() { PublisherModel model = new PublisherModel(); List<Publisher> listPublisher = db.Set<Publisher>().ToList(); foreach (var item in listPublisher) { model.PublisherList.Add(new SelectListItem() { Text = item.PublisherName, Value = item.ID.ToString() }); } ViewBag.PublishedList = model.PublisherList; return View(); } /// <summary>
/// 添加Book /// </summary>
/// <returns></returns>
[HttpPost] public ActionResult AddBook([Bind(Include = "BookName,BookAuthor,BookPrice,AddedDate,ModifiedDate,PublisherId")] Book model) { Book addBook = new Book() { AddedDate=model.AddedDate, BookAuthor=model.BookAuthor, BookName=model.BookName, BookPrice=model.BookPrice, ModifiedDate=model.ModifiedDate, PublisherId = Convert.ToInt32( Request["PublishedName"].ToString()) //這里因為出版商我用的是另外的Model,視圖中使用模型綁定只能用一個Model,所以修改和添加只能這樣搞了。
}; db.Entry(addBook).State = EntityState.Added; db.SaveChanges(); return RedirectToAction("Index"); } #endregion
#region UpdateBook
/// <summary>
/// 修改Book /// </summary>
/// <param name="bookId"></param>
/// <returns></returns>
public ActionResult UpdateBook(int bookId) { PublisherModel model = new PublisherModel(); List<Publisher> listPublisher = db.Set<Publisher>().ToList(); foreach (var item in listPublisher) { model.PublisherList.Add(new SelectListItem() { Text = item.PublisherName, Value = item.ID.ToString() }); } ViewBag.PublishedList = model.PublisherList; Book bookModel = db.Set<Book>().Where(s => s.ID == bookId).FirstOrDefault(); return View(bookModel); } /// <summary>
/// 修改Book /// </summary>
/// <param name="model"></param>
/// <returns></returns>
[HttpPost] public ActionResult UpdateBook([Bind(Include = "ID,BookName,BookAuthor,BookPrice,AddedDate,ModifiedDate,PublisherId")] Book model) //注意這里一定別忘記綁定 ID列哦
{ Book bookModel = db.Set<Book>().Where(s => s.ID == model.ID).FirstOrDefault(); if (bookModel != null) { Book updatemodel = new Book() { AddedDate = model.AddedDate, BookAuthor = model.BookAuthor, ID = model.ID, ModifiedDate = model.ModifiedDate, BookName = model.BookName, BookPrice = model.BookPrice, PublisherId = Convert.ToInt32(Request["PublishedName"].ToString())//這里因為出版商我用的是另外的Model,視圖中使用模型綁定只能用一個Model,所以修改和添加只能這樣搞了。
}; db.Entry(bookModel).CurrentValues.SetValues(updatemodel); //保存的另外一種方式
db.SaveChanges(); return RedirectToAction("Index"); } else { return View(model); } #region 保存的方式二
//db.Entry(model).State = EntityState.Modified; //db.SaveChanges(); //return RedirectToAction("Index");
#endregion } #endregion
#region DeleteBook
public ActionResult DeleteBook(int bookId) { Book model = db.Set<Book>().Where(s => s.ID == bookId).FirstOrDefault(); return View(model); } [HttpPost] public ActionResult DeleteBook(int bookId, FormCollection form) { Book model = db.Set<Book>().Where(s => s.ID == bookId).FirstOrDefault(); db.Entry(model).State = EntityState.Deleted; db.SaveChanges(); return RedirectToAction("Index"); } #endregion } }
視圖代碼,我使用MVC模板生成:【適當做修改】
AddBook視圖:
@model EF.Entity.Book @{ ViewBag.Title = "AddBook"; } <h2>AddBook</h2> @using (Html.BeginForm("AddBook","Book",FormMethod.Post)) { @Html.AntiForgeryToken() <div class="form-horizontal">
<h4>Book</h4>
<hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.AddedDate, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.AddedDate, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.AddedDate, "", new { @class = "text-danger" }) </div>
</div>
<div class="form-group"> @Html.LabelFor(model => model.ModifiedDate, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.ModifiedDate, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.ModifiedDate, "", new { @class = "text-danger" }) </div>
</div>
<div class="form-group"> @Html.LabelFor(model => model.BookName, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.BookName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.BookName, "", new { @class = "text-danger" }) </div>
</div>
<div class="form-group"> @Html.LabelFor(model => model.BookAuthor, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.BookAuthor, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.BookAuthor, "", new { @class = "text-danger" }) </div>
</div>
<div class="form-group"> @Html.LabelFor(model => model.BookPrice, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.BookPrice, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.BookPrice, "", new { @class = "text-danger" }) </div>
</div>
<div class="form-group"> @Html.LabelFor(model => model.PublisherId, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownList("PublishedName", ViewData["PublishedList"] as List<SelectListItem>) @*@Html.EditorFor(model => model.PublisherId, new { htmlAttributes = new { @class = "form-control" } })*@ @Html.ValidationMessageFor(model => model.PublisherId, "", new { @class = "text-danger" }) </div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div> } <div> @Html.ActionLink("Back to List", "Index") </div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
UpdateBook視圖:
@model EF.Entity.Book @{ ViewBag.Title = "UpdateBook"; } <h2>UpdateBook</h2> @using (Html.BeginForm("UpdateBook","Book",FormMethod.Post)) { @Html.AntiForgeryToken() <div class="form-horizontal">
<h4>Book</h4>
<hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(model => model.ID) <div class="form-group"> @Html.LabelFor(model => model.AddedDate, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.AddedDate, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.AddedDate, "", new { @class = "text-danger" }) </div>
</div>
<div class="form-group"> @Html.LabelFor(model => model.ModifiedDate, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.ModifiedDate, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.ModifiedDate, "", new { @class = "text-danger" }) </div>
</div>
<div class="form-group"> @Html.LabelFor(model => model.BookName, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.BookName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.BookName, "", new { @class = "text-danger" }) </div>
</div>
<div class="form-group"> @Html.LabelFor(model => model.BookAuthor, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.BookAuthor, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.BookAuthor, "", new { @class = "text-danger" }) </div>
</div>
<div class="form-group"> @Html.LabelFor(model => model.BookPrice, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.BookPrice, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.BookPrice, "", new { @class = "text-danger" }) </div>
</div>
<div class="form-group"> @Html.LabelFor(model => model.PublisherId, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownList("PublishedName", ViewData["PublishedList"] as List<SelectListItem>) @*@Html.EditorFor(model => model.PublisherId, new { htmlAttributes = new { @class = "form-control" } })*@ @Html.ValidationMessageFor(model => model.PublisherId, "", new { @class = "text-danger" }) </div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div> } <div> @Html.ActionLink("Back to List", "Index") </div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
注意:這里我只是把有改動的視圖貼了出來,其他的視圖,根據MVC模板生成之后,就不用管了。
@model IEnumerable<EF.Entity.Book> @{ ViewBag.Title = "Index"; } <h2>Index</h2>
<p> @Html.ActionLink("Create New", "AddBook") </p>
<table class="table">
<tr>
<th> @Html.DisplayNameFor(model => model.AddedDate) </th>
<th> @Html.DisplayNameFor(model => model.ModifiedDate) </th>
<th> @Html.DisplayNameFor(model => model.BookName) </th>
<th> @Html.DisplayNameFor(model => model.BookAuthor) </th>
<th> @Html.DisplayNameFor(model => model.BookPrice) </th>
<th> @Html.DisplayNameFor(model => model.PublisherId) </th>
<th></th>
</tr> @foreach (var item in Model) { <tr>
<td> @Html.DisplayFor(modelItem => item.AddedDate) </td>
<td> @Html.DisplayFor(modelItem => item.ModifiedDate) </td>
<td> @Html.DisplayFor(modelItem => item.BookName) </td>
<td> @Html.DisplayFor(modelItem => item.BookAuthor) </td>
<td> @Html.DisplayFor(modelItem => item.BookPrice) </td>
<td> @Html.DisplayFor(modelItem => item.PublisherId) </td>
<td> @Html.ActionLink("Edit", "UpdateBook", new { bookId = item.ID }) | @Html.ActionLink("Details", "DetailsBook", new { bookId = item.ID }) | @Html.ActionLink("Delete", "DeleteBook", new { bookId = item.ID }) </td>
</tr> } </table>
效果圖:




總結:1.下拉框實體中,構造函數初始化語句不能忘記。
2.修改的方式,有新變化看代碼;
3.模型綁定的時候,特別要注意,Bind的字段,修改的時候,Bind字段ID不能少。
