简体   繁体   中英

EF6 transaction error in ObjectContext

please can someone help i'm trying to use Transaction in EF6. it's my first try in transaction in .net. i have read the manual by Microsoft in their site. http://msdn.microsoft.com/en-us/data/dn456843.aspx and i would to use a transaction for user registration but nothing is working. Im using EF objectContext . here is a little piece of my code :

using (var context= new MyModelContainer())
{ 
 using(var dbContextTransaction = context.Database.BeginTransaction())
      {
       try 
         {
          // code here to create user
          context.savechanges();
          // code here to add role
         context.savechanges();

         dbContextTransaction.Commit(); 
        }
      catch 
         {
         dbContextTransaction.Rollback(); 
         }
     }
}

My problem is that Visual Studio does not even recognize Database.BeginTransaction() . may be because we are using objectContext ? i never use transaction. i change to use another database where our model is DbContext it's seems to work.

How can we use objectContext with transaction also (mean not distributed systems) ? any tutorial please ?

I tried transaction scope but it's seem to work but i read that it's for distributed system ((( it's means that performance going down. any suggestion ? thanks for your time !!!

Replace the line

using(var dbContextTransaction = context.Database.BeginTransaction())

with this:

using(var dbContextTransaction = new TransactionScope())

and remove the call to Rollback. TransactionScore will do what you need.

TransactionScope is compatible with distributed systems, but if you do not make a call to other db's and use it as described, then it is more than good enough for your needs. If you try to make a call to save to another db (for example) then it will require special privileges and an exception will be thrown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM