次の方法で共有


挿入、更新、削除の各操作

LINQ to SQL で InsertUpdate、および 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 を使用する開発者は、オブジェクト リレーショナル デザイナーを使用して、この目的でストアド プロシージャを開発できます。

こちらも参照ください