ASP.NET MVC - 資料庫



在本教程中建立的所有 ASP.NET MVC 應用程式中,我們一直從控制器向檢視模板傳遞硬編碼資料。但是,為了構建一個真正的 Web 應用程式,您可能希望使用一個真正的資料庫。在本章中,我們將瞭解如何使用資料庫引擎來儲存和檢索應用程式所需的資料。

為了儲存和檢索資料,我們將使用一種稱為 Entity Framework 的 .NET Framework 資料訪問技術來定義和處理模型。

Entity Framework (EF) 支援 Code First 技術,該技術允許您透過編寫簡單的類來建立模型物件,然後資料庫將根據您的類動態建立,從而實現非常簡潔和快速的開發工作流程。

讓我們來看一個簡單的示例,在該示例中,我們將為我們的示例新增對 Entity Framework 的支援。

步驟 1 - 要安裝 Entity Framework,請右鍵單擊您的專案,然後選擇 NuGet 包管理器 → 為解決方案管理 NuGet 包…

Install Entity Framework

它將開啟NuGet 包管理器。在搜尋框中搜索 Entity framework。

Search Entity Framework

選擇 Entity Framework 並單擊“安裝”按鈕。它將開啟“預覽”對話方塊。

Select Entity Framework

單擊“確定”繼續。

License Acceptance

單擊“我接受”按鈕開始安裝。

I Accept Button

安裝 Entity Framework 後,您將在輸出視窗中看到訊息,如上圖所示。

新增 DBContext

我們需要向 Employee 模型新增另一個類,該類將與 Entity Framework 通訊以使用以下程式碼檢索和儲存資料。

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

using System.Web;

namespace MVCSimpleApp.Models{
   public class Employee{
      public int ID { get; set; }
      public string Name { get; set; }
      public DateTime JoiningDate { get; set; }
      public int Age { get; set; }
   }
	
   public class EmpDBContext : DbContext{
      public EmpDBContext()
      { }
      public DbSet<Employee> Employees { get; set; }
   }
}

如上所示,EmpDBContext 派生自一個稱為DbContext的 EF 類。在此類中,我們有一個名為 DbSet 的屬性,它基本上表示您要查詢和儲存的實體。

連線字串

我們需要在 Web.config 檔案中的 <configuration> 標籤下為我們的資料庫指定連線字串。

<connectionStrings>
   <add name = "EmpDBContext" connectionString = "Data
   Source = (LocalDb)\v14.0;AttachDbFilename = |DataDirectory|\EmpDB.mdf;Initial
   Catalog = EmployeeDB;Integrated Security = SSPI;"
   providerName = "System.Data.SqlClient"/>
</connectionStrings>

您實際上不需要新增 EmpDBContext 連線字串。如果您未指定連線字串,則 Entity Framework 將在使用者的目錄中建立 localDB 資料庫,其名稱為 DbContext 類的完整限定名稱。對於此演示,我們將不新增連線字串以簡化操作。

現在,我們需要更新 EmployeeController.cs 檔案,以便我們實際上可以從資料庫中儲存和檢索資料,而不是使用硬編碼資料。

首先,我們新增建立一個私有的 EmpDBContext 類物件,然後更新 Index、Create 和 Edit 操作方法,如下面的程式碼所示。

using MVCSimpleApp.Models;
using System.Linq;
using System.Web.Mvc;

namespace MVCSimpleApp.Controllers {
   public class EmployeeController : Controller{
      private EmpDBContext db = new EmpDBContext();
      // GET: Employee
		
      public ActionResult Index(){
         var employees = from e in db.Employees
         orderby e.ID
         select e;
         return View(employees);
      }
		
      // GET: Employee/Create
      public ActionResult Create(){
         return View();
      }
		
      // POST: Employee/Create
      [HttpPost]
      public ActionResult Create(Employee emp){
         try{
            db.Employees.Add(emp);
            db.SaveChanges();
            return RedirectToAction("Index");
         }catch{
            return View();
         }
      }
		
      // GET: Employee/Edit/5
      public ActionResult Edit(int id){
         var employee = db.Employees.Single(m => m.ID == id);
         return View(employee);
      }
		
      // POST: Employee/Edit/5
      [HttpPost]
      public ActionResult Edit(int id, FormCollection collection){
         try{
            var employee = db.Employees.Single(m => m.ID == id);
            if (TryUpdateModel(employee)){
               //To Do:- database code
               db.SaveChanges();
               return RedirectToAction("Index");
            }
            return View(employee);
         }catch{
            return View();
         }
      }
   }
}

然後,我們使用以下 URL 執行此應用程式https://:63004/Employee。您將看到以下輸出。

Name JoiningDate Age

如您所見,檢視上沒有資料,這是因為我們尚未在 Visual Studio 建立的資料庫中新增任何記錄。

讓我們轉到 SQL Server 物件資源管理器,您將看到資料庫已建立,名稱與我們在 DBContext 類中使用的名稱相同。

DBContext Class

讓我們展開此資料庫,您將看到它有一個表,其中包含 Employee 模型類中的所有欄位。

Employee Model Class

要檢視此表中的資料,請右鍵單擊 Employees 表,然後選擇“檢視資料”。

Employee Table View Data

您將看到目前我們沒有記錄。

No Records Moment

讓我們直接在資料庫中新增一些記錄,如下面的螢幕截圖所示。

Add Records in Database

重新整理瀏覽器,您將看到資料現在已從資料庫更新到檢視。

Updated View

讓我們透過單擊“新建”連結從瀏覽器新增一條記錄。它將顯示 Create 檢視。

Create View

讓我們在以下欄位中新增一些資料。

Add Some Data

單擊“建立”按鈕,它將更新 Index 檢視並將此新記錄新增到資料庫。

New Record Database

現在讓我們轉到 SQL Server 物件資源管理器並重新整理資料庫。右鍵單擊 Employees 表,然後選擇“檢視資料”選單選項。您將看到該記錄已新增到資料庫中。

Record Added in Database
廣告