我有一个简单的查询来更新我数据库中的两个表
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();
}
}
但是如果我只是一个“throw new Exception();”他们之间是这样的
context.SaveChanges();
throw new Exception();
account accountItem = context.accounts.Where(x => x.userId == userId).FirstOfDefault();
用户表没有更新但是我的账户表没有更新,数据库保存了这些更改。如果抛出异常,我如何告诉我的数据库回滚更改?
谢谢
最佳答案
试试这个:
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();
}
关于c# Entity Framework 抛出异常但不回滚数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22556623/