分享方式:


作法:將資料列插入至資料庫

您可將物件新增至關聯的 LINQ to SQL Table<TEntity> 集合中,然後將變更提交至資料庫,藉以將資料列插入資料庫中。 LINQ to SQL 會轉譯變更為適當的 SQL INSERT 命令。

注意

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

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

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

若要將資料列插入至資料庫

  1. 建立包含所要提交之資料欄資料的新物件。

  2. 將新物件新增至與資料庫中目標資料表關聯的 LINQ to SQL Table 集合中。

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

範例

下列程式碼範例會建立 Order 型別的新物件,並且以適當的值填入 (Populate) 其中。 然後,將新物件加入至 Order 集合中。 最後,將變更當做 Orders 資料表中的新資料列,提交至資料庫。

// Create a new Order object.
Order ord = new Order
{
    OrderID = 12000,
    ShipCity = "Seattle",
    OrderDate = DateTime.Now
    // …
};

// Add the new object to the Orders collection.
db.Orders.InsertOnSubmit(ord);

// Submit the change to the database.
try
{
    db.SubmitChanges();
}
catch (Exception e)
{
    Console.WriteLine(e);
    // Make some adjustments.
    // ...
    // Try again.
    db.SubmitChanges();
}
' Create a new Order object.
Dim ord As New Order With _
{.OrderID = 12000, _
 .ShipCity = "Seattle", _
 .OrderDate = DateTime.Now}

' Add the new object to the Orders collection.
db.Orders.InsertOnSubmit(ord)

' Submit the change to the database.
Try
    db.SubmitChanges()
Catch e As Exception
    Console.WriteLine(e)
    ' Make some adjustments.
    ' ...
    ' Try again.
    db.SubmitChanges()
End Try

另請參閱