加入控制器(Controller)
此步驟主要是指定該控制器的資料庫來源類與模型類, 利用自動產生 View 來完成基本的CRUD操作頁面(若有勾選 使用版面配置頁, 則會套用 bootstrap).
專案結構變化如下
► MyModelsController.cs
► WebDBConnect.cs 內則會加入對應的資料集成員 MyModelspublic class MyModelsController : Controller { private WebDBConnect db = new WebDBConnect(); // GET: MyModels public ActionResult Index() { return View(db.MyModels.ToList()); } // GET: MyModels/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } MyModel myModel = db.MyModels.Find(id); if (myModel == null) { return HttpNotFound(); } return View(myModel); } // GET: MyModels/Create public ActionResult Create() { return View(); } // POST: MyModels/Create // 若要免於過量張貼攻擊,請啟用想要繫結的特定屬性,如需 // 詳細資訊,請參閱 http://go.microsoft.com/fwlink/?LinkId=317598。 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "Id,Title")] MyModel myModel) { if (ModelState.IsValid) { db.MyModels.Add(myModel); db.SaveChanges(); return RedirectToAction("Index"); } return View(myModel); } // GET: MyModels/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } MyModel myModel = db.MyModels.Find(id); if (myModel == null) { return HttpNotFound(); } return View(myModel); } // POST: MyModels/Edit/5 // 若要免於過量張貼攻擊,請啟用想要繫結的特定屬性,如需 // 詳細資訊,請參閱 http://go.microsoft.com/fwlink/?LinkId=317598。 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "Id,Title")] MyModel myModel) { if (ModelState.IsValid) { db.Entry(myModel).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(myModel); } // GET: MyModels/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } MyModel myModel = db.MyModels.Find(id); if (myModel == null) { return HttpNotFound(); } return View(myModel); } // POST: MyModels/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { MyModel myModel = db.MyModels.Find(id); db.MyModels.Remove(myModel); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } }
參考資源:public class WebDBConnect : DbContext { public WebDBConnect() : base("name=WebDBConnect") { } //加入控制器後自動產生的屬於該Model的資料集成員 public System.Data.Entity.DbSet<Web_ER_MVC.Models.MyModel> MyModels { get; set; } }