挿入、更新、および削除の各操作

オブジェクト モデルに対してオブジェクトの追加、変更、および削除を行うには、LINQ to SQL で InsertUpdate、および Delete の各操作を実行します。 既定では、LINQ to SQL によって SQL に対する操作が変換され、変更内容がデータベースに送信されます。

LINQ to SQL では、オブジェクトに対して行った変更内容の操作と維持に関して、最大限の柔軟性が提供されます。 クエリによって取得するか新規に作成することによりエンティティ オブジェクトが使用可能になった後で、通常のオブジェクトと同じようにそれらのオブジェクトをアプリケーションで変更できます。 つまり、それらに対して、値の変更、コレクションへの追加、およびコレクションからの削除を行うことができます。 LINQ to SQL では変更履歴が保持されるため、SubmitChanges を呼び出すと、変更内容をデータベースに送信できます。

Note

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 を呼び出すと、変更内容をデータベースに送信する SQL コマンドが LINQ to SQL によって自動的に生成され、実行されます。

Note

独自に作成したロジック (通常はストアド プロシージャ) を使用して、この動作をオーバーライドできます。 詳細については、「既定の動作をオーバーライドするときの開発者の責任」を参照してください。

Visual Studio を使用している開発者は、オブジェクト リレーショナル デザイナーを使用して、この目的のストアド プロシージャを開発できます。

関連項目