Consolidation of membership providers and dbcontext for one transaction

The MVC project first uses EF 5 and .NET 4.5 code.

I was looking for a way to wrap dbContext and SimpleMembershipProvider for one transaction. I tried using TransactionScope, but since the membership provider will open another connection, I get an exception (MSDTC on server "servername" is not available).

So, although I could use ObjectContext.Connection.BeginTransaction. The membership provider will not be part of the transaction, but the idea is to have it somewhere, where if it is not completed, the transaction will not be completed.

Book bk1 = default(Book); Book bk2 = default(Book); object obc = (IObjectContextAdapter)dbContext; obc.ObjectContext.Connection.Open(); using (tx == obc.ObjectContext.Connection.BeginTransaction) { bk1 = new Book { Name = "Book 1 Name", Location = "USA" }; dbContext.Books.Add(bk1); dbContext.SaveChanges(); bk2 = new Book { Name = "Book 2 Name. Book one Id is: " + bk1.Id, Location = "USA" }; dbContext.Books.Add(bk2); dbContext.SaveChanges(); // this is not part of the transaction, // however if it trhows an exception the transaction is aborted. // I'm assuming that if we got here, the commit won't fail... // But is it really true? WebSecurity.CreateUserAndAccount("username", "123456"); tx.Commit(); } 

In any case, based on the code above:

  • If WebSecurity.CreateUserAndAccount does not work, all of this fails as expected.
  • If any of the SaveChanges methods fails, again everything happens wrong, because we do not reach the point where CreateUserAndAccount is executed.

All this leads me to the question: Is it safe? I mean:

Is there a chance that the Commit method will throw an exception (due to an unsuccessful attempt) after the successful execution of DbContext.SaveChanges? If this happens, we will end up with an orphaned user, because the provider is not part of the transaction.

I appreciate any comments or advice on this.

Quick note: There is a good article explaining why I should use dbContext for the IObjectContextadapter instead of using my own connection property, but I can no longer find it.

+4
source share
1 answer

Yes, Commit can quit. One trivial example: connection fails. Of course, there are other cases.

You have several options:

  • Transactions in the same database will not develop into distributed ones if the connection is shared. This way you can use one connection for EF and your WebSecurity connection.
  • Run the distributed transaction controller on the server and live with escalation. Not the worst in the world.
  • Instead of using a transaction, change the order of operations so that a partially successful operation can be completed or canceled later. For example, users of orphans are discovered and cleaned.
+2
source

Source: https://habr.com/ru/post/1432982/


All Articles