Advertisement
Guest User

Untitled

a guest
May 9th, 2012
2,082
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None
  1. How to force only one transaction within multiple DbContext classes?
  2. public class MainContext : DbContext
  3. {
  4. public List<IPluginContext> ExternalContexts { get; set; }
  5.  
  6. // other stuff here
  7. }
  8.  
  9. public class PluginContext_A : DbContext, IPluginContext
  10. { /* Items from this context */ }
  11.  
  12. public class PluginContext_B : DbContext, IPluginContext
  13. { /* Items from this context */ }
  14.  
  15. using (var connection = new SqlConnection(connnectionString))
  16. {
  17. var c1 = new Context(connection);
  18. var c2 = new Context(connection);
  19.  
  20. c1.MyEntities.Add(new MyEntity() { Name = "A" });
  21. c2.MyEntities.Add(new MyEntity() { Name = "B" });
  22.  
  23. connection.Open();
  24.  
  25. using (var scope = new TransactionScope())
  26. {
  27. // This is necessary because DbContext doesnt't contain necessary methods
  28. ObjectContext obj1 = ((IObjectContextAdapter)c1).ObjectContext;
  29. obj1.SaveChanges(SaveOptions.DetectChangesBeforeSave);
  30.  
  31. ObjectContext obj2 = ((IObjectContextAdapter)c2).ObjectContext;
  32. obj2.SaveChanges(SaveOptions.DetectChangesBeforeSave);
  33.  
  34. scope.Complete();
  35.  
  36. // Only after successful commit of both save operations we can accept changes
  37. // otherwise in rollback caused by second context the changes from the first
  38. // context will be already accepted = lost
  39.  
  40. obj1.AcceptAllChanges();
  41. obj2.AcceptAllChanges();
  42. }
  43. }
  44.  
  45. public Context(DbConnection connection) : base(connection,false) { }
Advertisement
RAW Paste Data Copied
Advertisement