Entity Framework 基本架構
- Entity:實體,對應概念模型中的類別。
- Entity Data Model (EDM):包含 CSDL (概念)、SSDL (儲存)、MSL (映射) 三層。
- LINQ to Entities:對實體進行 LINQ 查詢。
- Entity SQL:類 SQL 查詢語言,針對概念模型。
- ObjectContext:管理實體狀態、變更追蹤與資料庫互動的核心。
CRUD 完整程式碼 - Demo.aspx.cs
資料繫結
void BindData() {
using (var ctx = new NorthwindEntities()) {
GridView1.DataSource = ctx.Categories; // ObjectQuery<Categories>
GridView1.DataBind();
}
}
新增 (含關聯實體)
protected void btnAddCategory_Click(object sender, EventArgs e) {
using (var ctx = new NorthwindEntities()) {
// CreateCategories 為靜態工廠方法,參數含必要屬性 (含自增 PK 可給任意值)
var category = Categories.CreateCategories(-1, txtCategoryName.Text);
category.Description = txtDescription.Text;
// 批次加入關聯產品
for (int i = 0; i < 10; i++) {
category.Products.Add(new Products { ProductName = "測試用" + i });
}
ctx.AddToCategories(category); // 加入上下文,狀態變為 Added
ctx.SaveChanges(); // 寫入資料庫,自動取回自增 PK
Page.ClientScript.RegisterStartupScript(this.GetType(), "js",
"alert('CategoryID: " + category.CategoryID + "');", true);
}
GridView1.EditIndex = -1;
BindData();
}
刪除 (級聯刪除關聯實體)
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) {
using (var ctx = new NorthwindEntities()) {
var categoryId = (int)GridView1.DataKeys[e.RowIndex].Value;
var category = ctx.Categories.First(p => p.CategoryID == categoryId);
// 載入關聯集合以便級聯刪除 (若 DB 有 Cascade Delete 且 EDM 設定 OnDelete=Cascade 可省略)
category.Products.Load();
ctx.DeleteObject(category); // 標記為 Deleted
ctx.SaveChanges();
}
GridView1.EditIndex = -1;
BindData();
}
查詢關聯資料
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) {
using (var ctx = new NorthwindEntities()) {
var categoryId = (int)GridView1.SelectedDataKey.Value;
var products = ctx.Products.Where(p => p.Categories.CategoryID == categoryId);
GridView2.DataSource = products; // IQueryable<Products>
GridView2.DataBind();
}
}
更新
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) {
using (var ctx = new NorthwindEntities()) {
var categoryId = (int)GridView1.DataKeys[e.RowIndex].Value;
var category = ctx.Categories.First(p => p.CategoryID == categoryId);
// 直接修改實體屬性,上下文自動偵測變更
category.CategoryName = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
category.Description = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
ctx.SaveChanges();
}
GridView1.EditIndex = -1;
BindData();
}
重點總結
CreateEntityName 工廠方法建立新實體,必填屬性為參數。
AddToEntitySetName 將實體加入上下文追蹤。
- 修改實體屬性後直接呼叫
SaveChanges(),EF 自動產生 UPDATE 語句。
- 刪除使用
DeleteObject(),配合 Load() 載入導航屬性實現級聯刪除。
ObjectQuery<T> 可直接繫結至資料控制項,支援延遲執行。
完整原始碼:https://www.bianceng.net/dotnet/201212/805.htm