【发布时间】:2015-06-04 04:00:35
【问题描述】:
我的项目是用Ninject开发的,比如我写了2个函数来插入或更新到数据库
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();
}
}
在 Controller 中,我声明了相同的 DbContext 并使用事务:
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();
}
}
}
}
那么如果InsertToDB()或UpdateToDB()抛出任何异常,事务可以回滚吗?
我很担心,因为我觉得Controller和Repository的_context不一样,我现在无法测试,帮帮我,谢谢!
【问题讨论】:
-
SaveChanges提交,因此如果抛出异常,更改将不会持续。不是吗? -
@JNF 是的,如果抛出异常,我希望所有操作回滚:)
-
我的意思是,据我所知,您的代码已经做到了
标签: c# linq entity-framework transactions