
於 2016 發表的.NET技術圖書《Entity Framework 實務精要》,除了完整討論 Entity Framework 技術內容,同時收錄了 ASP.NET WebForms 與 ASP.NET MVC 的整合說明,這一篇節錄其中最簡單的 WebForms 設定示範說明。
網際網路發展逐漸成熟,網頁作為應用程式的其中一種操作介面已經相當長見,而 ASP.NET 簡化了 Entity Framework 在 Web 應用程式的開發工作,它提供 EntityDataSource 控制項支援資料模型的存取操作。
建立一個 ASP.NET Web 應用程式專案,並且將其命名為 WebFormsEF,指定 Web Forms 範本,完成新專案的建立。接下來建立所需的資料模型,於專案 Model 資料夾按一下滑鼠右鍵展開功能表,於其中點選「加入>新增項目」,開啟「加入新增項目」對話方塊。
選取「ADO.NET 實體資料模型」,於下方的「名稱」欄位,輸入KTStoreModel,按一下「新增」按鈕,建立所需的資料模型檔案。
選擇「來自資料庫的 EF Designer」,按「下一步」選取測試用資料庫,然後逐步完成建立作業。
在專案結構的Models 資料夾中,現在多了一個 KTStoreModel.edmx 實體資料模型檔案,將其展開可以看到其中的檔案結構。現在新增一個Web 表單 ProductList.aspx,於其中配置一個新的 GridView 控制項將其命名為 Products 。
測試用的實體資料模型連接的資料庫中包含了一個測試資料表 Product,撰寫程式碼利用GridView 將資料表的內容顯示網頁上,開啟表單ProductList.aspx 後置程式碼檔案 ProductList.aspx.cs。
using System;
using System.Linq;
using WebFormsEF.Models;
namespace WebFormsEF
{
public partial class ProductList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public IQueryable<Product> SelectProduct()
{
KTStoreEntities entities = new KTStoreEntities();
var products = entities.Product;
return products;
}
}
}
引用命名空間 WebFormsEF.Models ,並且建立 SelectProduct() 函式內容,取得實體資料模型中的 Product 集合物件並且回傳作為 GridView 控制項的資料內容。開啟表單 ProductList.aspx 切換至原始檔模式,進行以下的設定。
<%@ Page Language="C#" AutoEventWireup="true" … %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div style="margin:1em auto;width:70%;">
<asp:GridView ID="Products" runat="server"
SelectMethod="SelectProduct" Width="100%" >
</asp:GridView>
</div>
</form>
</body>
</html>
其中將 GridView 的 SelectMethod 屬性設定為上述建立的函式 SelectProduct() ,如此一來當 GridView 於網頁載入之後,便會顯示 Prodcut 資料表的所有資料內容。
沒有留言:
張貼留言