插入、更新和刪除作業

您可以藉由新增、變更和移除物件模型中的物件,以便在 LINQ to SQL 中執行 InsertUpdateDelete 作業。 根據預設,LINQ to SQL 會將您的動作轉譯成 SQL 並將變更提交至資料庫。

LINQ to SQL 提供相當大的彈性來操作和保存您對物件所做的變更。 一旦取得實體物件 (透過查詢加以擷取或重新加以建構),您就可以將它們變更為應用程式中的典型物件。 也就是說,您可以變更這些實體物件的值,將它們加入至集合中,以及從集合中加以移除。 LINQ to SQL 會追蹤這些變更,而且在您呼叫 SubmitChanges 時準備好將變更傳送回資料庫。

注意

LINQ to SQL 不支援或辨識串聯刪除作業。 如果您要刪除有限制式之資料表中的資料列,必須在資料庫的外部索引鍵限制式中設定 ON DELETE CASCADE 規則,或者使用您自己的程式碼,先刪除使父物件無法刪除的子物件。 否則,會擲回例外狀況。 如需詳細資訊,請參閱如何:將資料列從資料庫刪除

下列摘錄會使用 Northwind 範例資料庫中的 CustomerOrder 類別。 為了簡單起見,並不會顯示類別定義。

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 命令,以便將變更傳送回資料庫。

注意

您通常可以透過預存程序 (Stored Procedure),使用自訂邏輯來覆寫這個行為。 如需詳細資訊,請參閱開發人員覆寫預設行為的責任

使用 Visual Studio 的開發人員可以使用物件關聯式設計工具來為此開發預存程序。

另請參閱