Tag Archives: c#

LINQ to SQL DataContext and Transactions

17 Sep

I am posting this as a way to remember it, since I am starting a real project using LINQ to SQL soon.

LINQ to SQL orders the objects with pending changes based on their dependencies. LINQ to SQL starts a transaction to wrap the SQL statements. The SQL statements are issued one by one. Any errors detected by the database cause the process to stop and all the changes are rolled back. The DataContext still contains the pending changes enabling you to try and resolve the issue and SubmitChanges again as in this example.

   1: Northwnd db = new Northwnd(@"c:\northwnd.mdf");
   2: // Make changes here. 
   3: try
   4: {
   5:     db.SubmitChanges();
   6: }
   7: catch (ChangeConflictException e)
   8: {
   9:     Console.WriteLine(e.Message);
  10:     // Make some adjustments.
  11:     // ...
  12:     // Try again.
  13:     db.SubmitChanges();
  14: }