Share via


How to: Insert Rows Into the Database (LINQ to SQL)

You insert rows into a database by adding objects to the associated LINQ to SQL Table<TEntity> collection and then submitting the changes to the database. LINQ to SQL translates your changes into the appropriate SQL INSERT commands.

Note

You can override LINQ to SQL default methods for Insert, Update, and Delete database operations. For more information, see Customizing Insert, Update, and Delete Operations (LINQ to SQL).

Developers using Visual Studio can use the Object Relational Designer to develop stored procedures for the same purpose. Object Relational Designer (O/R Designer)
Object Relational Designer (O/R Designer)

The following steps assume that a valid DataContext connects you to the Northwind database. For more information, see How to: Connect to a Database (LINQ to SQL).

To insert a row into the database

  1. Create a new object that includes the column data to be submitted.

  2. Add the new object to the LINQ to SQL Table collection associated with the target table in the database.

  3. Submit the change to the database.

Example

The following code example creates a new object of type Order and populates it with appropriate values. It then adds the new object to the Order collection. Finally, it submits the change to the database as a new row in the Orders table.

' 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
// 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();
}

See Also

Tasks

How to: Assign Stored Procedures to Perform Updates, Inserts, and Deletes (O/R Designer)

Concepts

DataContext Methods (O/R Designer)

Other Resources

How to: Manage Change Conflicts (LINQ to SQL)

Making and Submitting Data Changes (LINQ to SQL)