Simple LINQ 2 SQL example

I’ve been using LINQ to SQL for some time, and each time I come back to the same example, so it’s about time I shared the example:

 

      //  Create a DataContext.
      Northwind db = new Northwind();

 

      //  Retrieve customer LAZYK.
      Customer cust = (from c in db.Customers
                       where c.CustomerID == “LAZYK”
                       select c).Single<Customer>();

 

      //  Update the contact name.
      cust.ContactName = “John Smith”;

 

      try
      {
        //  Save the changes.
        db.SubmitChanges();
      }

      //  Detect concurrency conflicts.
      catch (ChangeConflictException)
      {
        //  Resolve conflicts.
        db.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges);
      }