插入、更新和删除操作

在 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 的开发人员可以使用对象关系设计器来为此开发存储过程。

另请参阅