How to: Update Rows in the Database

You can update rows in a database by modifying member values of the objects associated with the LINQ to SQL Table<TEntity> collection and then submitting the changes to the database. LINQ to SQL translates your changes into the appropriate SQL UPDATE 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.

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 update a row in the database

  1. Query the database for the row to be updated.

  2. Make desired changes to member values in the resulting LINQ to SQL object.

  3. Submit the changes to the database.

Example

The following example queries the database for order #11000, and then changes the values of ShipName and ShipVia in the resulting Order object. Finally, the changes to these member values are submitted to the database as changes in the ShipName and ShipVia columns.

// Query the database for the row to be updated.
var query =
    from ord in db.Orders
    where ord.OrderID == 11000
    select ord;

// Execute the query, and change the column values
// you want to change.
foreach (Order ord in query)
{
    ord.ShipName = "Mariner";
    ord.ShipVia = 2;
    // Insert any additional changes to column values.
}

// Submit the changes to the database.
try
{
    db.SubmitChanges();
}
catch (Exception e)
{
    Console.WriteLine(e);
    // Provide for exceptions.
}
' Query the database for the row to be updated.
Dim ordQuery = _
    From ord In db.Orders _
    Where ord.OrderID = 11000 _
    Select ord

' Execute the query, and change the column values
' you want to change.
For Each ord As Order In ordQuery
    ord.ShipName = "Mariner"
    ord.ShipVia = 2
    ' Insert any additional changes to column values.
Next

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

See also