mysql - c# entity framework throw exception but no roll back on database -
i have simple query updates 2 tables in database
public void updatelogins(int userid) { using (var context = new storemanagerentities()) { user item = context.users.where(x => x.id == userid).firstofdefault(); item.logins += 1; context.savechanges(); account accountitem = context.accounts.where(x => x.userid == userid).firstofdefault(); accountitem.logins += 1; context.savechanges(); } }
but if "throw new exception();" between them so
context.savechanges(); throw new exception(); account accountitem = context.accounts.where(x => x.userid == userid).firstofdefault();
the user table not updated account table has not been updated, , database saves these changes. how can tell database rollback changes if exception thrown?
thanks
try :
using (transactionscope txscope = new transactionscope()) { using (var context = new storemanagerentities()) { user item = context.users.where(x => x.id == userid).firstofdefault(); item.logins += 1; context.savechanges(); account accountitem = context.accounts.where(x => x.userid == userid).firstofdefault(); accountitem.logins += 1; context.savechanges(); } txscope.complete(); }
Comments
Post a Comment