How to: Update Rows in the Database (LINQ to SQL)

How to: Update Rows in the Database (LINQ to SQL)

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.


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

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.
catch (Exception e)
    // Provide for exceptions.

© 2015 Microsoft