Entity Framework 事务
结合第一篇的代码
public class BaseRepository : ITransaction, IDisposable { private XFDbContext dbContext;
之所以将数据上下文抽离出来,而不是每次使用都using,这样做就是为了在调用的时候,满足是同一个上下文,因为同一个上下文是事务性质的,在提交之前,如果一旦有异常,所有操作都会回滚
public bool Del(string id) { bool result = false; BaseRepository respository = new BaseRepository(); respository.BeginTransaction(); try { //1.删除关系 string sqlStr_d = "delete from S_UserRoles where UserID=@UserIDd"; SqlParameter[] paras_d = { new SqlParameter("@UserIDd", id), }; respository.ExecuteSqlCommand(sqlStr_d, paras_d); //2.删除主表 respository.Delete<S_Users>(m => m.UserID == id); result = respository.Commit() > ; } catch (Exception ex) { respository.Rollback(); } finally { respository.Dispose(); } return result; }
思路是什么呢?
BeginTransaction()
更改IsTransaction属性,表示现在开始是一个实务操作,这样每一个单元操作都不会做提交
Commit()
做最后的提交,会判断一下存不存在DbContextTransaction,如果存在一并提交
Rollback()
也会判断一下存不存在DbContextTransaction,如果存在一并回滚
public void BeginTransaction() { if (dbContext.Database.CurrentTransaction == null) { dbContext.Database.BeginTransaction(); } this.IsTransaction = true; } public int Commit() { int reault = dbContext.SaveChanges(); this.IsTransaction = false; DbContextTransaction transaction = dbContext.Database.CurrentTransaction; if (transaction != null) { transaction.Commit(); transaction.Dispose(); reault += ; } return reault; } public void Rollback() { this.IsTransaction = false; DbContextTransaction transaction = dbContext.Database.CurrentTransaction; if (transaction != null) { transaction.Rollback(); transaction.Dispose(); } } public bool IsTransaction { get; private set; }