共用方式為


作法:從資料庫刪除資料列

您可以從資料表相關的集合移除對應的 LINQ to SQL 物件,並刪除資料庫中的資料列。 LINQ to SQL 會平移您的變更至適當的 SQL DELETE 命令。

LINQ to SQL 不支援或無法辨識串聯刪除作業。 如果您要刪除有條件約束之資料表中的資料列,必須完成下列其中一項工作:

  • 在資料庫的外部索引鍵條件約束中設定 ON DELETE CASCADE 規則。

  • 使用您自己的程式碼,先刪除使父物件無法刪除的子物件。

否則,會擲回例外狀況。 請參閱本主題稍後的第二個程式碼範例。

注意

您可以覆寫 InsertUpdateDelete 資料庫作業的 LINQ to SQL 預設方法。 如需詳細資訊,請參閱自訂插入、更新和刪除作業 (機器翻譯)

使用 Visual Studio 時,開發人員可以使用物件關聯式設計工具開發相同用途的預存程序。

下列步驟假設一個有效的 DataContext 會將您連接至 Northwind 資料庫。 如需詳細資訊,請參閱操作說明:連線資料庫

若要從資料庫刪除資料列

  1. 查詢資料庫,以找出要刪除的資料列。

  2. 呼叫 DeleteOnSubmit 方法。

  3. 將變更提交至資料庫。

範例 1

下列第一個程式碼範例會查詢資料庫中屬於訂單 #11000 的訂單明細、將這些訂單明細標示為刪除,然後將這些變更送出至資料庫。

// Query the database for the rows to be deleted.
var deleteOrderDetails =
    from details in db.OrderDetails
    where details.OrderID == 11000
    select details;

foreach (var detail in deleteOrderDetails)
{
    db.OrderDetails.DeleteOnSubmit(detail);
}

try
{
    db.SubmitChanges();
}
catch (Exception e)
{
    Console.WriteLine(e);
    // Provide for exceptions.
}
' Query the database for the rows to be deleted.
Dim deleteOrderDetails = _
    From details In db.OrderDetails() _
    Where details.OrderID = 11000 _
    Select details

For Each detail As OrderDetail In deleteOrderDetails
    db.OrderDetails.DeleteOnSubmit(detail)
Next

Try
    db.SubmitChanges()
Catch ex As Exception
    Console.WriteLine(ex)
    ' Provide for exceptions
End Try

範例 2

在下列第二個範例中,目標是要移除某張訂單 (#10250)。 這段程式碼會先檢查 OrderDetails 資料表,查看要移除的訂單是否在該處有子系。 如果訂單有子系,則會先將子系標示為移除,再將訂單標示為移除。 DataContext 會將實際的刪除放置在正確的訂單中,使傳送到資料庫的刪除命令得以遵守資料庫條件約束。

Northwnd db = new Northwnd(@"c:\northwnd.mdf");

db.Log = Console.Out;

// Specify order to be removed from database
int reqOrder = 10250;

// Fetch OrderDetails for requested order.
var ordDetailQuery =
    from odq in db.OrderDetails
    where odq.OrderID == reqOrder
    select odq;

foreach (var selectedDetail in ordDetailQuery)
{
    Console.WriteLine(selectedDetail.Product.ProductID);
    db.OrderDetails.DeleteOnSubmit(selectedDetail);
}

// Display progress.
Console.WriteLine("detail section finished.");
Console.ReadLine();

// Determine from Detail collection whether parent exists.
if (ordDetailQuery.Any())
{
    Console.WriteLine("The parent is present in the Orders collection.");
    // Fetch Order.
    try
    {
        var ordFetch =
            (from ofetch in db.Orders
             where ofetch.OrderID == reqOrder
             select ofetch).First();
        db.Orders.DeleteOnSubmit(ordFetch);
        Console.WriteLine("{0} OrderID is marked for deletion.", ordFetch.OrderID);
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        Console.ReadLine();
    }
}
else
{
    Console.WriteLine("There was no parent in the Orders collection.");
}

// Display progress.
Console.WriteLine("Order section finished.");
Console.ReadLine();

try
{
    db.SubmitChanges();
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
    Console.ReadLine();
}

// Display progress.
Console.WriteLine("Submit finished.");
Console.ReadLine();
Dim db As New Northwnd("c:\northwnd.mdf")

db.Log = Console.Out
' Specify order to be removed from database.
Dim reqOrder As Integer = 10252

' Fetch OrderDetails for requested order.
Dim ordDetailQuery = _
From odq In db.OrderDetails _
Where odq.OrderID = reqOrder _
Select odq

For Each selectedDetail As OrderDetail In ordDetailQuery
    Console.WriteLine(selectedDetail.Product.ProductID)
    db.OrderDetails.DeleteOnSubmit(selectedDetail)
Next

' Display progress.
Console.WriteLine("Detail section finished.")
Console.ReadLine()

' Determine from Detail collection whether parent exists.
If ordDetailQuery.Any Then
    Console.WriteLine("The parent is present in the Orders collection.")
    ' Fetch order.
    Try
        Dim ordFetch = _
        (From ofetch In db.Orders _
         Where ofetch.OrderID = reqOrder _
         Select ofetch).First()

        db.Orders.DeleteOnSubmit(ordFetch)
        Console.WriteLine("{0} OrderID is marked for deletion.,", ordFetch.OrderID)

    Catch ex As Exception
        Console.WriteLine(ex.Message)
        Console.ReadLine()
    End Try

Else
    Console.WriteLine("There was no parent in the Orders collection.")

End If


' Display progress.
Console.WriteLine("Order section finished.")
Console.ReadLine()

Try
    db.SubmitChanges()

Catch ex As Exception
    Console.WriteLine(ex.Message)
    Console.ReadLine()

End Try

' Display progress.
Console.WriteLine("Submit finished.")
Console.ReadLine()

另請參閱