您可以藉由在物件模型中新增、變更和移除物件,在 LINQ to SQL 中執行 Insert、 Update和 Delete 作業。 根據預設,LINQ to SQL 會將動作轉譯為 SQL,並將變更提交至資料庫。
LINQ to SQL 提供在操作和保存您對物件所做變更時的最大彈性。 只要實體物件可供使用(透過查詢擷取它們,或透過重新建構它們),您就可以將其變更為應用程式中的典型物件。 也就是說,您可以變更其值、將其新增至集合,以及從集合中移除它們。 LINQ to SQL 會追蹤您的變更,並準備好在呼叫 SubmitChanges時將其傳輸回資料庫。
備註
LINQ to SQL 不支援或辨識串聯刪除作業。 如果您想要刪除資料表中具有條件約束的數據列,您必須在資料庫中的外鍵條件約束中設定 ON DELETE CASCADE 規則,或使用您自己的程式碼先刪除防止刪除父物件的子物件。 否則會拋出例外狀況。 如需詳細資訊,請參閱 如何:從資料庫刪除數據列。
下列摘錄使用 Northwind 範例資料庫中的 Customer 類別和 Order 類別。 類別定義並非為了簡潔起見而顯示。
Northwnd db = new Northwnd(@"c:\Northwnd.mdf");
// Query for a specific customer.
var cust =
(from c in db.Customers
where c.CustomerID == "ALFKI"
select c).First();
// Change the name of the contact.
cust.ContactName = "New Contact";
// Create and add a new Order to the Orders collection.
Order ord = new Order { OrderDate = DateTime.Now };
cust.Orders.Add(ord);
// Delete an existing Order.
Order ord0 = cust.Orders[0];
// Removing it from the table also removes it from the Customer’s list.
db.Orders.DeleteOnSubmit(ord0);
// Ask the DataContext to save all the changes.
db.SubmitChanges();
Dim db As New Northwnd("…\Northwnd.mdf")
Dim cust As Customer = _
(From c In db.Customers _
Where c.CustomerID = "ALFKI" _
Select c) _
.First()
' Change the name of the contact.
cust.ContactName = "New Contact"
' Create and add a new Order to Orders collection.
Dim ord As New Order With {.OrderDate = DateTime.Now}
cust.Orders.Add(ord)
' Delete an existing Order.
Dim ord0 As Order = cust.Orders(0)
' Removing it from the table also removes it from
' the Customer’s list.
db.Orders.DeleteOnSubmit(ord0)
' Ask the DataContext to save all the changes.
db.SubmitChanges()
當您呼叫 SubmitChanges 時,LINQ to SQL 會自動生成並執行所需的 SQL 命令,以將您的變更傳回至資料庫。
備註
您可以使用自己的自定義邏輯來覆寫此行為,通常是透過預存程式。 如需詳細資訊,請參閱 開發人員在覆寫預設行為中的責任。
使用 Visual Studio 的開發人員可以使用物件關係型設計工具來為此開發預存程式。