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);
      }

 

blog comments powered by Disqus

About the author

You have probably figured out by now that my name is Bryan Avery (if not, please refer to your browser's address field).  Technology is more than a career to me - it is both a hobby and a passion.  I'm an ASP.NET/C# Developer at heart...

Month List