我有这个返回bool的方法:
using(Entities dbContext = new Entities())
{
using (DbContextTransaction myTransaction = dbContext.Database.BeginTransaction())
{
//Get data from database
//check data from database
//if my data is the expected: return true;
//???: rollback or something to do or is it enough with the return?
//if not is expected:
//update data;
//dbContext.Savechages();
//myTransaction.Commit();
//return true;
}
}
我的疑问是,如果我不需要对数据做更多的事情,是否足够返回true或者建议进行回滚,或者提交没有SaveChanges?
感谢。
答案 0 :(得分:1)
你应该在开始事务之前检查你的数据,你在从DB读取数据时不需要开始trasnaction,因为你逻辑中的第一部分没有任何更新,插入...而你不需要任何提交或回滚< / p>
实际上你的代码应该是这样的
using(Entities dbContext = new Entities())
{
//Get data from database
//check data from database
//if my data is the expected: return true;
using (DbContextTransaction myTransaction = dbContext.Database.BeginTransaction())
{
//if not is expected:
try
{
//update data;
//dbContext.Savechages();
//myTransaction.Commit();
//return true;
}
catch(Exception ex)
{
transaction.Rollback();
......
return false;
}
}
}