This documentation is archived and is not being maintained.

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.


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. For more information, see Object Relational Designer (O/R Designer) and 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.

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.
Order ord = new Order
    OrderID = 12000,
    ShipCity = "Seattle",
    OrderDate = DateTime.Now
    // …

// Add the new object to the Orders collection.

// Submit the change to the database.
catch (Exception e)
    // Make some adjustments.
    // ...
    // Try again.