c# - Can LINQ BeginTransaction works with new Context? -


my project using ninject develop, example, wrote 2 functions insert or update database

public class personrepository : ipersonrepository {      private readonly dbcontext _context;      public personrepository(dbcontext context) {         _context = context; }      public void inserttodb(person obj) {         _context.persons.add(obj);         _context.savechanges(); }         public void updatetodb(person obj) {         _context.persons.attach(obj);         _context.savechanges();     }    } 

and in controller, declare same dbcontext , using transaction:

public class personcontroller : controller {      private readonly dbcontext _context;     private readonly ipersonrepository _repository;      public personcontroller(dbcontext context, ipersonrepository repository) {         _context = context;         _repository = repository;     }      public actionresult index() {         return view();     }      [httppost]     public actionresult executetodb(person person1, person person2) {         using (var transaction = _context.database.begintransaction(isolationlevel.readcommitted)) {             try {                 _repository.inserttodb(person1);                 _repository.updatetodb(person2);                  transaction.commit();             } catch (exception) {                 transaction.rollback();             }         }     } } 

so if inserttodb() or updatetodb() throw exception, can transaction rollback?

i worry because think _context of controller , repository different, not able test right now, me, thanks!

you have 3 options here. first, can configure ninject use same instance of dbcontext both personcontroller , personrepository. configuring binding use inrequestscope(). then, can call begintransaction , it's same context.

alternatively, add begintransaction, committransaction, , rollbacktrasaction methods our irepository class, , implement these in repository.

a third option create new transactionscope() rather calling begintransaction on context.

using (transactionscope scope = new transactionscope(transactionscopeoption.required,         new transactionoptions { isolationlevel = isolationlevel.readcommitted,                                  timeout = transactionmanager.maximumtimeout })) {     _repository.inserttodb(person1);     _repository.updatetodb(person2);      // if exception occurs, complete not called, transaction     // automatically rolled when dispose called when using()     // goes out of scope.  if complete called, commit called.     scope.complete(); } 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -