Share via


插入、更新和删除操作

通过在对象模型中添加、更改和移除对象,可以在 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 命令。

备注

您可以使用自己的自定义逻辑来重写此行为,这通常是通过存储过程来实现的。 有关详细信息,请参阅开发人员在重写默认行为中的责任

使用 Visual Studio 的开发人员可以使用对象关系设计器来开发用于实现此目的的存储过程。

请参阅