.NET Magazine國際中文電子雜誌
作 者:許薰尹
審 稿:張智凱
文章編號:N141215501
出刊日期:2014/11/19
開發工具:Visual Studio 2013 Ultimate Update 3
版本:.NET Framework 4.5.X
在ASP.NET MVC的網站應用程式之中,常常會需要整合資料庫,呈現資料庫多個資料表之中的內。另外也需要提供一個使用者介面,讓使用者新增、刪除、修改、查詢資料庫資料。本篇文章將介紹如何建立一個ASP.NET MVC5應用程式,並利用ADO.NET Entity Framework Code First來設計可以呈現Master-Detail(主表明細)檢視的資料存取程式碼。
建立ASP.NET MVC 5應用程式專案
我們從建立一個ASP.NET MVC5應用程式專案開始。從Visual Studio 2013開發工具 -「File」-「New」-「Project」,在「New Project」對話盒中,確認視窗上方.NET Framework的目標版本為「.NET Framework 4.5.1」,選取左方「Installed」-「Template」-「Visual C#」程式語言,從「Web」分類中,選取「ASP.NET Web Application」。本例設定專案名稱為「MasterDetailsDemo」,按下「OK」鍵,請參考下圖所示:

圖 1:建立一個ASP.NET MVC5應用程式專案。
在「New ASP.NET Project」對話盒中選取「Empty」項目,勾選下方的「MVC」項目,然後按下「OK」按鈕建立專案,請參考下圖所示:

圖 2:選取「Empty」的「MVC」項目。
安裝Entity Framework套件
預設空白的MVC專案沒有引用Entity Framework,我們可以使用Nuget套件管理員從Nuget.org網站下載「Entity Framework」函式庫。在「Solution Explorer」視窗選取專案名稱。從Visual Studio 2013開發工具「TOOLS」-「Library Package Manager」-「Package Manage Console」開啟「Package Manage Console」視窗,然後在提示字元中輸入install-package指令,並使用「-version」指定安裝Entity Framework 6.1.1版本:
Install-Package EntityFramework -Version 6.1.1
得到的執行結果如下圖所示:

圖 3:使用Nuget套件管理員安裝Entity Framework套件。
設計模型(Model)
首先我們來定義一個Employee模型來描述員工資料,以及一個Department模型來描述部門資訊。部門與員工有一對多的關係。從Visual Studio 2013開發工具-「Solution Explorer」- 專案-「Models」資料夾上方按滑鼠右鍵,從快捷選單選擇「Add」- 「New Item」,開啟「Add New Item」對話盒,從右上方文字方塊輸入「Class」關鍵字搜尋,選取Class,設定名稱為「Employee」,然後按下「Add」按鈕,建立新類別,請參考下圖所示:

圖 4:建立Employee類別。
在Employee類別之中,加入以下程式碼,定義員工該有的屬性,其中DepartmentId 屬性用來和Department模型關聯用,Department屬性用來取得相關聯的部門資訊:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace MasterDetailsDemo.Models {
public class Employee {
[DisplayName( "員工編號" )]
public int EmployeeId { get; set; }
[DisplayName( "部門編號" )]
public int DepartmentId { get; set; }
[DisplayName( "員工姓名" )]
public string EmployeeName { get; set; }
[DisplayName( "生日" )]
[DisplayFormat( DataFormatString = "{0:yyyy/MM/dd}" , ApplyFormatInEditMode = true )]
public DateTime BirthDay { get; set; }
[DisplayName( "已婚" )]
public bool IsMarried { get; set; }
[DisplayName( "部門" )]
public Department Department { get; set; }
}
}
重複上個步驟,新增Department類別來描述部門資料,其中Projects屬性用來描述Department模型相關聯的Employee:
using MasterDetailsDemo.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace MasterDetailsDemo.Models {
public class Department {
[DisplayName( "部門編號" )]
public int DepartmentId { get; set; }
[DisplayName( "部門名稱" )]
public string DepartmentName { get; set; }
[DisplayName( "員工清單" )]
public virtual ICollection<Employee> Employees { get; set; }
}
}
選取「Build」-「Build Solution」編譯目前的專案,確認程式碼能正確編譯。
定義DbContext類別
下一步,讓我們來定義DbContext類別,以便利用Entity Framework Code First方式建立以及存取資料庫。從「Models」資料夾上方按滑鼠右鍵,從快捷選單選擇「Add」- 「New Item」,開啟「Add New Item」對話盒,從右上方文字方塊輸入「ado.net」搜尋,選取「ADO.NET Entity Data Model」,設定名稱為「EmployeesContext」,然後按下「Add」按鈕,請參考下圖所示:

圖 5:新增「ADO.NET Entity Data Model」。
下一步,選取「Empty Code First model」項木,建立一個空白的Code First模型(注意:Visual Studio 2013要更新到Update 3才能看到這個選項),請參考下圖所示:

圖 6:建立一個空白的Code First模型。
按下「Finish」按鈕之後,Visual Studio 2013將產生一個EmployeesContext.cs檔案,包含以下的程式碼:
namespace MasterDetailsDemo.Models {
using System;
using System.Data.Entity;
using System.Linq;
public class EmployeesContext : DbContext {
// Your context has been configured to use a 'EmployeesContext' connection string from your application's
// configuration file (App.config or Web.config). By default, this connection string targets the
// 'MasterDetailsDemo.Models.EmployeesContext' database on your LocalDb instance.
//
// If you wish to target a different database and/or database provider, modify the 'EmployeesContext'
// connection string in the application configuration file.
public EmployeesContext( )
: base( "name=EmployeesContext" ) {
}
// Add a DbSet for each entity type that you want to include in your model. For more information
// on configuring and using a Code First model, see
http://go.microsoft.com/fwlink/?LinkId=390109.
// public virtual DbSet<MyEntity> MyEntities { get; set; }
}
//public class MyEntity
//{
// public int Id { get; set; }
// public string Name { get; set; }
//}
}
並在Web.config檔案中,加上連結到資料庫的連接字串,目前產生的組態檔是將資料建置在(LocalDB)資料庫:
<connectionStrings>
<add name="EmployeesContext" connectionString="data source=(LocalDb)\v11.0;initial catalog=MasterDetailsDemo.Models.EmployeesContext;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
修改EmployeesContext類別的程式碼,在類別中宣告Employees、Departments兩個屬性:
public class EmployeesContext : DbContext {
public EmployeesContext( )
: base( "name=EmployeesContext" ) {
}
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Department> Departments { get; set; }
}
選取「Build」-「Build Solution」編譯目前的專案,確認程式碼能正確編譯。
檢視模型
使用Entity Framework Code First方式設計資料存取程式時,因為模型(Model)未來會建置在記憶體之中,不需使用EDMX檔案描述,因此在開發階段看不到模型的長像。你可以安裝Entity Framework Power Tools工具以視覺化的方式檢視模型。從Visual Studio 2013工具的 「Tools」選單,選取「Extensions and Updates」,從「Online」搜尋以及下載「Entity Framework Power Tools Beta4」。
Entity Framework Power Tools工具安裝完成之後,就可以在「Solution Explorer」視窗-專案中的「EmployeesContext.cs」檔案上方按滑鼠右鍵,從快捷選單選擇「Entity Framework」- 「View Entity Data Model(Ready-only)」項目,來檢視模型,請參考下圖所示:

圖 7:檢視模型。
目前的模型,請參考下圖所示:

圖 8:目前的模型。
建立資料庫與初始資料表資料
接下來,我們將使用Entity Framework Code First Migration(資料移轉)方式來建立資料庫與初始資料表資料。從Visual Studio 2013開發工具「TOOLS」-「Library Package Manager」-「Package Manage Console」開啟「Package Manage Console」視窗,然後在提示字元中輸入enable-migrations指令,啟用資料移轉功能:
enable-migrations
得到的執行結果如下圖所示:

圖 9:啟用資料移轉功能。
接著Visual Studio 2013工具會自動在專案中產生一個「Migrations」資料夾,其中包含一個Configuration.cs檔案。我們可改寫其中的Seed方法,建立Department、與Employee物件,這樣就可以利用Entity Framework,新增初始資料到資料庫。注意初始化的程式碼,其中王彼得與李小明將同屬於電腦部,而劉大同則隸屬於會計部:
protected override void Seed( MasterDetailsDemo.Models.EmployeesContext context ) {
Department d1 = new Department {
DepartmentName = "電腦部" ,
};
Department d2 = new Department {
DepartmentName = "會計部" ,
};
context.Departments.AddOrUpdate(
e => e.DepartmentName ,
d1 ,
d2 ,
new Department {
DepartmentName = "業務部" ,
}
);
context.Employees.AddOrUpdate(
e => e.EmployeeName ,
new Employee {
EmployeeName = "王彼得" ,
DepartmentId = 1 ,
BirthDay = new DateTime( 2010 , 1 , 2 ) ,
IsMarried = true ,
Department = d1
} ,
new Employee {
EmployeeName = "李小明" ,
DepartmentId = 1 ,
BirthDay = new DateTime( 2011 , 12 , 12 ) ,
IsMarried = false ,
Department = d1
} ,
new Employee {
EmployeeName = "劉大同" ,
DepartmentId = 2 ,
BirthDay = new DateTime( 2000 , 5 , 6 ) ,
IsMarried = true ,
Department = d2
}
);
}
選取「Build」-「Build Solution」編譯目前的專案,確認程式碼能正確編譯。
更新資料庫
從Visual Studio 2013開發工具「TOOLS」-「Library Package Manager」-「Package Manage Console」開啟「Package Manage Console」視窗,然後在提示字元中輸入update-database,更新資料庫:
update-database
得到的執行結果如下圖所示:

圖 10:更新資料庫。
先驗證資料庫與資料表資料是否正確建立。開啟「Server Explorer」視窗,在「Data Connections」項目上按滑鼠右鍵,從快捷選單之中選取「Add Connection」項目。請參考下圖所示,在「Add Connection」視窗中,設定以下屬性:
- 資料來源 (Data Source) :Microsoft SQL Server (SQLClient)。
- Server name欄位:輸入「(localdb)\v11.0」。
- Log on to server:選取「Use Windows Authentication」。
- Select or enter a database name欄位:選擇「MasterDetailsDemo.Models.EmployeesContext」資料庫。
完成後按下「OK」按鈕,檢視新建立的資料表與欄位資訊,請參考下圖所示:

圖 11:檢視新建立的資料表與欄位資訊。
展開「Server Explorer」視窗-「Data Connections」-「EmployeesContext」資料庫 -「Tables」- 「Departments」資料表,在「Department」資料表上按滑鼠右鍵,從快捷選單中選取「Show Table Data」顯示Departments資料表所有資料,確認新增了三筆資料:

圖 12:Department資料表所有資料。
在「Departments」資料表上按滑鼠右鍵,從快捷選單中選取「Open Table Definition」,就可以看到Departments資料表的結構描述資訊,其中DepartmentId將是主鍵欄位(Primary Key)請參考下圖所示:

圖 13:Departments資料表的結構描述資訊。
工具利用以下的SQL陳述句來建立資料表,並自動設定一個Primary Key條件約束:
CREATE TABLE [dbo].[Departments] (
[DepartmentId] INT IDENTITY (1, 1) NOT NULL,
[DepartmentName] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_dbo.Departments] PRIMARY KEY CLUSTERED ([DepartmentId] ASC)
);
Employees資料表的內容,請參考下圖所示,將包含三筆資料:

圖 14:檢視Employees資料表的內容。
工具產生的SQL陳述句如下,從中可得知,將利用Employees資料表的DepartmentId欄位與Departments資料表的DepartmentId欄位建立Foreign Key:
CREATE TABLE [dbo].[Employees] (
[EmployeeId] INT IDENTITY (1, 1) NOT NULL,
[DepartmentId] INT NOT NULL,
[EmployeeName] NVARCHAR (MAX) NULL,
[BirthDay] DATETIME NOT NULL,
[IsMarried] BIT NOT NULL,
CONSTRAINT [PK_dbo.Employees] PRIMARY KEY CLUSTERED ([EmployeeId] ASC),
CONSTRAINT [FK_dbo.Employees_dbo.Departments_DepartmentId] FOREIGN KEY ([DepartmentId]) REFERENCES [dbo].[Departments] ([DepartmentId]) ON DELETE CASCADE
);
GO
CREATE NONCLUSTERED INDEX [IX_DepartmentId]
ON [dbo].[Employees]([DepartmentId] ASC);
設計控制器(Controller)
接著我們來建立一個EmployeesController來存取資料庫Employees資料表資料。從Visual Studio 2013開發工具-「Solution Explorer」視窗- 專案 -「Controllers」資料夾上方按滑鼠右鍵,從快捷選單選擇「Add」- 「New Scaffolded Item」,開啟「Add Scaffold」對話盒,請參考下圖所示:

圖 15:設計控制器(Controller)。
在「Add Scaffold」對話盒中選取「MVC 5 Controller with views, using Entity Framework」項目,然後按下「Add 」按鈕,請參考下圖所示:

圖 16:選取「MVC 5 Controller with views, using Entity Framework」項目。
在「Add Controller」對話盒中,設定「Model class」為Employee;「Data context class」為「EmployeesContext」;控制器名稱為「EmployeesController」;勾選「Generate views」,然後按下「Add 」按鈕,請參考下圖所示:

圖 17:新增控制器。
Visual Studio 產生的EmployeesController程式如下,裏頭包含基礎的新增、刪除、修改、查詢的Action Method程式碼:
public class EmployeesController : Controller
{
private EmployeesContext db = new EmployeesContext();
// GET: Employees
public ActionResult Index()
{
var employees = db.Employees.Include( e => e.Department );
return View( employees.ToList() );
}
// GET: Employees/Details/5
public ActionResult Details( int? id )
{
if (id == null)
{
return new HttpStatusCodeResult( HttpStatusCode.BadRequest );
}
Employee employee = db.Employees.Find(id);
if (employee == null)
{
return HttpNotFound();
}
return View(employee);
}
// GET: Employees/Create
public ActionResult Create()
{
ViewBag.DepartmentId = new SelectList( db.Departments, "DepartmentId", "DepartmentName" );
return View();
}
// POST: Employees/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create( [Bind( Include = "EmployeeId,DepartmentId,EmployeeName,BirthDay,IsMarried")] Employee employee )
{
if (ModelState.IsValid)
{
db.Employees.Add( employee );
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.DepartmentId = new SelectList( db.Departments, "DepartmentId", "DepartmentName", employee.DepartmentId );
return View( employee );
}
// GET: Employees/Edit/5
public ActionResult Edit( int? id )
{
if (id == null)
{
return new HttpStatusCodeResult( HttpStatusCode.BadRequest );
}
Employee employee = db.Employees.Find( id );
if (employee == null)
{
return HttpNotFound();
}
ViewBag.DepartmentId = new SelectList( db.Departments, "DepartmentId", "DepartmentName", employee.DepartmentId );
return View( employee );
}
// POST: Employees/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit( [Bind(Include = "EmployeeId,DepartmentId,EmployeeName,BirthDay,IsMarried")] Employee employee )
{
if ( ModelState.IsValid )
{
db.Entry( employee ).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.DepartmentId = new SelectList( db.Departments, "DepartmentId", "DepartmentName", employee.DepartmentId );
return View( employee );
}
// GET: Employees/Delete/5
public ActionResult Delete( int? id )
{
if (id == null)
{
return new HttpStatusCodeResult( HttpStatusCode.BadRequest );
}
Employee employee = db.Employees.Find(id);
if (employee == null)
{
return HttpNotFound();
}
return View(employee);
}
// POST: Employees/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed( int id )
{
Employee employee = db.Employees.Find(id);
db.Employees.Remove( employee );
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose( bool disposing )
{
if ( disposing )
{
db.Dispose();
}
base.Dispose( disposing );
}
}
選取「Build」-「Build Solution」編譯目前的專案,確認程式碼能正確編譯。從「Solution Explorer」視窗- 選取Views\Employees資料夾下的Index.cshtml檔案,按CTRL+F5執行Index 檢視,執行結果參考如下,顯示員工清單,每一筆員工資料前方都會自動顯示所屬部門:

圖 18:顯示員工清單。
Index檢視
工具產生的Index.cshtml內容如下,其中使用「model.Department.DepartmentName」語法,來找到Employee相關聯的Department之DepartmentName:
@model IEnumerable<MasterDetailsDemo.Models.Employee>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor( model => model.Department.DepartmentName )
</th>
<th>
@Html.DisplayNameFor( model => model.EmployeeName )
</th>
<th>
@Html.DisplayNameFor( model => model.BirthDay )
</th>
<th>
@Html.DisplayNameFor( model => model.IsMarried )
</th>
<th></th>
</tr>
@foreach ( var item in Model ) {
<tr>
<td>
@Html.DisplayFor( modelItem => item.Department.DepartmentName )
</td>
<td>
@Html.DisplayFor( modelItem => item.EmployeeName )
</td>
<td>
@Html.DisplayFor( modelItem => item.BirthDay )
</td>
<td>
@Html.DisplayFor( modelItem => item.IsMarried )
</td>
<td>
@Html.ActionLink( "Edit", "Edit", new { id=item.EmployeeId }) |
@Html.ActionLink( "Details", "Details", new { id=item.EmployeeId }) |
@Html.ActionLink( "Delete", "Delete", new { id=item.EmployeeId })
</td>
</tr>
}
</table>
</body>
</html>
Details檢視
點選Index網頁上任一筆員工後方的「Details」超連結,可以顯示員工詳細資訊,但網頁執行時,預設範本產生的程式碼沒有正確地顯示部門名稱,請參考下圖所示:

圖 19:顯示Details資料。
工具產生的Details.cshtml內容如下:
@model IEnumerable<MasterDetailsDemo.Models.Employee>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width=device-width" />
<title>Index</title>
</head>
<body>
<p>
@Html.ActionLink( "Create New", "Create" )
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor( model => model.Department.DepartmentName)
</th>
<th>
@Html.DisplayNameFor( model => model.EmployeeName)
</th>
<th>
@Html.DisplayNameFor( model => model.BirthDay)
</th>
<th>
@Html.DisplayNameFor( model => model.IsMarried)
</th>
<th></th>
</tr>
@foreach ( var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Department.DepartmentName)
</td>
<td>
@Html.DisplayFor( modelItem => item.EmployeeName)
</td>
<td>
@Html.DisplayFor( modelItem => item.BirthDay)
</td>
<td>
@Html.DisplayFor( modelItem => item.IsMarried)
</td>
<td>
@Html.ActionLink( "Edit", "Edit", new { id=item.EmployeeId }) |
@Html.ActionLink( "Details", "Details", new { id=item.EmployeeId }) |
@Html.ActionLink( "Delete", "Delete", new { id=item.EmployeeId })
</td>
</tr>
}
</table>
</body>
</html>
我們可以略加修改控制器中的Details方法,利用Include方法,將Employee相關聯的Department資料找出來:
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Employee employee = db.Employees.Include( e => e.Department ).FirstOrDefault(e=>e.EmployeeId==id );
if (employee == null)
{
return HttpNotFound();
}
return View(employee);
}
重新執行程式,則Details檢視的執行結果請參考下圖所示:

圖 20:顯示Details資料。
Edit檢視
若點選Index網頁上任一筆員工後方的「Edit」超連結,可以進入Edit檢視,以編輯員工資訊,工具產生的程式碼很聰明地自動以下拉式清單,來顯示員工所屬的部門名稱,請參考下圖所示:

圖 21:Edit檢視。
Edit檢視的程式碼如下,使用Html.DropDownList顯示下拉式選單:
@model MasterDetailsDemo.Models.Employee
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Edit</title>
</head>
<body>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4> Employee </h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor( model => model.EmployeeId)
<div class="form-group">
@Html.LabelFor( model => model.DepartmentId, "DepartmentId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList( "DepartmentId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor( model => model.DepartmentId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor( model => model.EmployeeName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor( model => model.EmployeeName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor( model => model.EmployeeName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.BirthDay, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.BirthDay, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.BirthDay, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.IsMarried, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.IsMarried)
@Html.ValidationMessageFor(model => model.IsMarried, "", new { @class = "text-danger" })
</div>
</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>
</body>
</html>
Delete檢視
若點選Index網頁上任一筆員工後方的「Delete」超連結,可以進入Delete檢視,請參考下圖所示,同樣地,工具產生的程式碼預設不顯示部門名稱,需自行修改,在此不再重複累述。

圖 22:Delete檢視。
Delete檢視的程式碼如下:
@model MasterDetailsDemo.Models.Employee
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Delete</title>
</head>
<body>
<h3>Are you sure you want to delete this?</h3>
<div>
<h4>Employee</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Department.DepartmentName)
</dt>
<dd>
@Html.DisplayFor(model => model.Department.DepartmentName)
</dd>
<dt>
@Html.DisplayNameFor(model => model.EmployeeName)
</dt>
<dd>
@Html.DisplayFor(model => model.EmployeeName)
</dd>
<dt>
@Html.DisplayNameFor(model => model.BirthDay)
</dt>
<dd>
@Html.DisplayFor(model => model.BirthDay)
</dd>
<dt>
@Html.DisplayNameFor(model => model.IsMarried)
</dt>
<dd>
@Html.DisplayFor(model => model.IsMarried)
</dd>
</dl>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
<div class="form-actions no-color">
<input type="submit" value="Delete" class="btn btn-default" /> |
@Html.ActionLink("Back to List", "Index")
</div>
}
</div>
</body>
</html>
Create檢視
最後我們看一下Create檢視,部門的資料同樣採用下拉式選單讓使用者選取,以避免輸入時出錯,請參考下圖所示:

圖 23:Create檢視。
Create檢視的程式碼如下:
@model MasterDetailsDemo.Models.Employee
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Create</title>
</head>
<body>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.DepartmentId, "DepartmentId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("DepartmentId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.DepartmentId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.EmployeeName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.EmployeeName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.EmployeeName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.BirthDay, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.BirthDay, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.BirthDay, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.IsMarried, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.IsMarried)
@Html.ValidationMessageFor(model => model.IsMarried, "", new { @class = "text-danger" })
</div>
</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>
</body>
</html>
小結
在這一篇文章中,我們利用Visual Studio 2013的功能,自動產生Entity Framework Code First的資料存取相關程式碼來讀取相關聯的資料表資料。參考下圖,在下一篇文章中,我們將延續這個情境,再新增一個Project模型,以描述Employee與Project之間有一對多的關係。

圖 24:Employee、Department與Project的關係。