ASP.Net MVC與SQL Server資料庫操作

在本教學之前,創建的所有ASP.NET MVC應用程式中,我們一直在將來自控制器的硬編碼數據傳遞給視圖範本。 但是,構建真正的Web應用程式,可能需要使用真實的資料庫。 在本章中,我們將學習如何使用資料庫引擎來存儲和檢索應用程式所需的數據。

要存儲和檢索數據,我們將使用Entity框架的.NET Framework數據訪問技術來定義和使用模型。

Entity框架(EF)支持Code First技術,該技術允許通過編寫簡單的類來創建模型對象,然後從類中隨時創建資料庫,從而實現非常乾淨和快速的開發流程。

下麵來看一個簡單的例子,我們將在這個例子中添加Entity框架的支持來訪問資料庫。

第1步 - 創建一個專案:MVCDatabaseAccess,如下所示 -

要安裝Entity Framework框架,右鍵單擊專案,然後選擇管理NuGet程式包 ,在彈出的介面中搜索:Entity framework,如下圖所示 -

選擇Entity framework,然後點擊“Install”按鈕。它將打開預覽對話框 -

接受安裝協議,如下圖所示 -

Entity framework框架安裝成功,會看到下麵的截圖中所示的綠色“勾”的圖示。如下圖所示 -

添加DBContext

我們需要向Employee模型添加另一個類,該類將與Entity Framework進行通信,以使用以下代碼檢索和保存數據。

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

using System.Web;
namespace MVCDatabaseAccess.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=MY-PC;Initial Catalog=testdb;Integrated Security=True" providerName = "System.Data.SqlClient"/>
  </connectionStrings>

實際上不需要添加EmpDBContext連接字串。如果不指定連接字串,則Entity Framework將使用DbContext類的標準名稱在用戶目錄中創建localDB資料庫。 對於這個示例,我們不會添加連接字串來簡化。

現在需要更新EmployeeController.cs檔,以便可以從資料庫中保存和檢索數據,而不是使用硬編碼的數據。

首先,添加創建一個私有的EmpDBContext類對象,然後更新IndexCreateEdit動作方法,如下面的代碼所示。參考以下代碼 -

using MVCDatabaseAccess.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCDatabaseAccess.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:http://localhost:61868/Employee運行這個應用程式。將看到以下輸出。

正如所看到的,這個視圖上沒有數據,但是程式已經自動創建了一個表:Employee,這是因為我們還沒有在資料庫表中添加任何記錄。

進入SQL Server對象資源管理器,會看到資料庫使用與我們在DBContext類中創建的相同的名稱 - Employee

展開這個資料庫,會看到它有一個包含Employee模型類中的所有字段的表。

要查看此表中的數據,請右鍵單擊Employees表並選擇查看數據。應該會看到目前沒有數據記錄。我們直接在資料庫的Employee表中添加一些記錄,如下圖所示 -

刷新流覽器,應該會看到數據現在已經更新到了視圖中了。如下圖所示 -

點擊“Create New” 鏈接,從流覽器中添加一條記錄,它將顯示創建視圖。在下面的字段中添加一些數據。

點擊Create按鈕,它會更新索引視圖以及添加這個新的記錄到資料庫。

現在打開SQL Server對象資源管理器並刷新資料庫。右鍵單擊Employees表並選擇查看數據菜單選項。應該就會看到該記錄被添加到資料庫中了。


上一篇: ASP.Net MVC模型綁定 下一篇: ASP.Net MVC驗證