entity framework - ASP.NET MVC5/EF6 - AutoSaveChanges prematurely commiting Unit of Work -
so found prematurely commiting (source):
one issue aware of userstore class not play when using unit of work design pattern. specifically, userstore invokes savechanges in every method call default, makes easy prematurely commit unit of work. change behavior, change autosavechanges flag on userstore.
so problem changing flag makes working identity objects harder. example, when creating new user don't id.
also how save changes in class accountcontroller in default don't have (or need) declare applicationdbcontext , have usermanager , signinmanager? i'd need instantiate new applicationdbcontext , save that, isn't solution.
i found solution consisted of using database transactions, this:
var dbcontext = // instance of applicationdbcontext var usermanager = // instance of applicationusermanager using (var transaction = dbcontext.database.begintransaction(isolationlevel.readcommitted)) { try { var user = // crate applicationuser var usercreateresult = await usermanger.createasync(user, password); if(!usercreateresult.succeeded) { // list of errors in usercreateresult.errors transaction.rollback(); return usercreateresult.errors; } // new guid user saved user.id property var userid = user.id; var addtoroleresult = await usermanager.addtoroleasync(user.id, "my role name"); if(!addtoroleresult.succeeded) { // deal errors transaction.rollback(); return addtoroleresult.errors; } // if got here, worked fine, commit transaction transaction.commit(); } catch (exception exception) { transaction.rollback(); // log exception throw; } } (source: https://stackoverflow.com/a/27367675/3194577)
but i'm confused how fixes anything. lets have execution order this:
- add/update in context, don't save database
- execute usermanager.createasync save context (which don't want yet)
if surround transaction, still happen same way, except rollback if i'd want to, right? doesn't help, helps if go wrong, , never want wrong in first place why want control on when saves. maybe i'm confused how transactions work.
Comments
Post a Comment