鍍金池/ 教程/ C#/ ASP.Net MVC與SQL Server數(shù)據(jù)庫(kù)操作
ASP.Net MVC簡(jiǎn)介
ASP.Net MVC過(guò)濾器
ASP.Net MVC視圖
ASP.Net MVC安全
ASP.Net MVC手腳架
ASP.Net MVC控制器
ASP.Net MVC與SQL Server數(shù)據(jù)庫(kù)操作
ASP.Net MVC NuGet包管理
ASP.Net MVC入門程序
ASP.Net MVC Razor
ASP.Net MVC Bootstrap
ASP.Net MVC單元測(cè)試
ASP.Net MVC動(dòng)作
ASP.Net MVC模式
ASP.Net MVC選擇器
ASP.Net MVC開(kāi)發(fā)環(huán)境配置
ASP.Net MVC生命周期
ASP.Net MVC模型綁定
ASP.Net MVC自托管(本地主機(jī)部署)
ASP.Net MVC驗(yàn)證
ASP.Net MVC緩存
ASP.Net MVC數(shù)據(jù)模型
ASP.Net MVC路由
ASP.Net MVC教程
ASP.Net MVC助手
ASP.Net MVC數(shù)據(jù)注解
ASP.Net MVC Web API

ASP.Net MVC與SQL Server數(shù)據(jù)庫(kù)操作

在本教程之前,創(chuàng)建的所有ASP.NET MVC應(yīng)用程序中,我們一直在將來(lái)自控制器的硬編碼數(shù)據(jù)傳遞給視圖模板。 但是,構(gòu)建真正的Web應(yīng)用程序,可能需要使用真實(shí)的數(shù)據(jù)庫(kù)。 在本章中,我們將學(xué)習(xí)如何使用數(shù)據(jù)庫(kù)引擎來(lái)存儲(chǔ)和檢索應(yīng)用程序所需的數(shù)據(jù)。

要存儲(chǔ)和檢索數(shù)據(jù),我們將使用Entity框架的.NET Framework數(shù)據(jù)訪問(wèn)技術(shù)來(lái)定義和使用模型。

Entity框架(EF)支持Code First技術(shù),該技術(shù)允許通過(guò)編寫簡(jiǎn)單的類來(lái)創(chuàng)建模型對(duì)象,然后從類中隨時(shí)創(chuàng)建數(shù)據(jù)庫(kù),從而實(shí)現(xiàn)非常干凈和快速的開(kāi)發(fā)流程。

下面來(lái)看一個(gè)簡(jiǎn)單的例子,我們將在這個(gè)例子中添加Entity框架的支持來(lái)訪問(wèn)數(shù)據(jù)庫(kù)。

第1步 - 創(chuàng)建一個(gè)項(xiàng)目:MVCDatabaseAccess,如下所示 -

要安裝Entity Framework框架,右鍵單擊項(xiàng)目,然后選擇管理NuGet程序包 ,在彈出的界面中搜索:Entity framework,如下圖所示 -

選擇Entity framework,然后點(diǎn)擊“Install”按鈕。它將打開(kāi)預(yù)覽對(duì)話框 -

接受安裝協(xié)議,如下圖所示 -

當(dāng)Entity framework框架安裝成功,會(huì)看到下面的截圖中所示的綠色“勾”的圖標(biāo)。如下圖所示 -

添加DBContext

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

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是從一個(gè)名為DbContext的EF類派生的。在這個(gè)類中有一個(gè)名為DbSet的屬性它基本上表示想查詢和保存的實(shí)體。

連接字符串

我們需要在Web.config文件中的<configuration>標(biāo)記下為數(shù)據(jù)庫(kù)指定連接字符串。

 <connectionStrings>
    <add name = "EmpDBContext" connectionString = "Data Source=MY-PC;Initial Catalog=testdb;Integrated Security=True" providerName = "System.Data.SqlClient"/>
  </connectionStrings>

實(shí)際上不需要添加EmpDBContext連接字符串。如果不指定連接字符串,則Entity Framework將使用DbContext類的標(biāo)準(zhǔn)名稱在用戶目錄中創(chuàng)建localDB數(shù)據(jù)庫(kù)。 對(duì)于這個(gè)示例,我們不會(huì)添加連接字符串來(lái)簡(jiǎn)化。

現(xiàn)在需要更新EmployeeController.cs文件,以便可以從數(shù)據(jù)庫(kù)中保存和檢索數(shù)據(jù),而不是使用硬編碼的數(shù)據(jù)。

首先,添加創(chuàng)建一個(gè)私有的EmpDBContext類對(duì)象,然后更新Index,CreateEdit動(dòng)作方法,如下面的代碼所示。參考以下代碼 -

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();
            }
        }
    }
}

然后訪問(wèn)以下URL:http://localhost:61868/Employee運(yùn)行這個(gè)應(yīng)用程序。將看到以下輸出。

正如所看到的,這個(gè)視圖上沒(méi)有數(shù)據(jù),但是程序已經(jīng)自動(dòng)創(chuàng)建了一個(gè)表:Employee,這是因?yàn)槲覀冞€沒(méi)有在數(shù)據(jù)庫(kù)表中添加任何記錄。

進(jìn)入SQL Server對(duì)象資源管理器,會(huì)看到數(shù)據(jù)庫(kù)使用與我們?cè)?code>DBContext類中創(chuàng)建的相同的名稱 - Employee

展開(kāi)這個(gè)數(shù)據(jù)庫(kù),會(huì)看到它有一個(gè)包含Employee模型類中的所有字段的表。

要查看此表中的數(shù)據(jù),請(qǐng)右鍵單擊Employees表并選擇查看數(shù)據(jù)。應(yīng)該會(huì)看到目前沒(méi)有數(shù)據(jù)記錄。我們直接在數(shù)據(jù)庫(kù)的Employee表中添加一些記錄,如下圖所示 -

刷新瀏覽器,應(yīng)該會(huì)看到數(shù)據(jù)現(xiàn)在已經(jīng)更新到了視圖中了。如下圖所示 -

點(diǎn)擊“Create New” 鏈接,從瀏覽器中添加一條記錄,它將顯示創(chuàng)建視圖。在下面的字段中添加一些數(shù)據(jù)。

點(diǎn)擊Create按鈕,它會(huì)更新索引視圖以及添加這個(gè)新的記錄到數(shù)據(jù)庫(kù)。

現(xiàn)在打開(kāi)SQL Server對(duì)象資源管理器并刷新數(shù)據(jù)庫(kù)。右鍵單擊Employees表并選擇查看數(shù)據(jù)菜單選項(xiàng)。應(yīng)該就會(huì)看到該記錄被添加到數(shù)據(jù)庫(kù)中了。