Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- How to force only one transaction within multiple DbContext classes?
- public class MainContext : DbContext
- {
- public List<IPluginContext> ExternalContexts { get; set; }
- // other stuff here
- }
- public class PluginContext_A : DbContext, IPluginContext
- { /* Items from this context */ }
- public class PluginContext_B : DbContext, IPluginContext
- { /* Items from this context */ }
- using (var connection = new SqlConnection(connnectionString))
- {
- var c1 = new Context(connection);
- var c2 = new Context(connection);
- c1.MyEntities.Add(new MyEntity() { Name = "A" });
- c2.MyEntities.Add(new MyEntity() { Name = "B" });
- connection.Open();
- using (var scope = new TransactionScope())
- {
- // This is necessary because DbContext doesnt't contain necessary methods
- ObjectContext obj1 = ((IObjectContextAdapter)c1).ObjectContext;
- obj1.SaveChanges(SaveOptions.DetectChangesBeforeSave);
- ObjectContext obj2 = ((IObjectContextAdapter)c2).ObjectContext;
- obj2.SaveChanges(SaveOptions.DetectChangesBeforeSave);
- scope.Complete();
- // Only after successful commit of both save operations we can accept changes
- // otherwise in rollback caused by second context the changes from the first
- // context will be already accepted = lost
- obj1.AcceptAllChanges();
- obj2.AcceptAllChanges();
- }
- }
- public Context(DbConnection connection) : base(connection,false) { }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement