How to: Insert Rows Into the Database


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.

System_CAPS_ICON_note.jpg 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.

Developers using Visual Studio can use the Object Relational Designer to develop stored procedures for the same purpose.

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

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.

How to: Manage Change Conflicts
DataContext Methods (O/R Designer)
How to: Assign stored procedures to perform updates, inserts, and deletes (O/R Designer)
Making and Submitting Data Changes