LINQ to SQL Update Operation using C#
The Update operation of LINQ to SQL allows modifying an old entity object available in the associated entity table of DataContext collection. After manipulating the object into the collection, LINQ to SQL auto-generates a SQL script when you call SubmitChanges method that transmits changes back to the database. In this tutorial we have used the NorthwindDataContext class created in the previous tutorial: Creating LINQ to SQL Entity Classes using O/R Designer. While creating the DataContext for Northwind SQL database we added only two tables, categories and products. Now we will perform the LINQ to SQL update operation to modify the category name of a specific category into the categories table using C# code.
Example
// create datacontext object
NorthwindDataContext db = new NorthwindDataContext();
// get record that is to be updated
Category category = (from c in db.Categories
where c.CategoryID == 9
select c).Single();
// modify category name
category.CategoryName = "Old Category";
try
{
// submit changes to the database
db.SubmitChanges();
}
catch
{
throw new Exception("Could not save changes.");
}
The above C# code illustrates the update operation using LINQ to SQL. In the code sample, first we have created an object for NorthwindDataContext class to access the collection of categories. Then we have used a LINQ query and Queryable Single method to retrieve a single category from the database where CategoryID is 9. In the next statement we have assigned a new category name to the CategoryName property of category class. Finally, we have called the SubmitChanges method to save the modifications into the database.
Continue to the next tutorial: LINQ to SQL Delete Operation using C# to learn how to remove a record from the database.

* will not be published
* hint: http://www.example.com