如果一个表带有自增列的,那么在事务处理的过程中,如果抑制了提交,自增的序号就不会得到,如果我们需要得到那怎么办呢?可以临时提交,但是既然提交了就要考虑到事务回滚,否则无法满足数据的一致性
public bool Add(StationView modelView) { bool result = false; this.DbContext.BeginTransaction(); try { Station station = new Station { ShopID = modelView.ShopID, StationNo = modelView.StationNo, IsOccupy = modelView.IsOccupy }; StationRepository.Insert(station); this.DbContext.SaveChanges(); Device device = new Device { StationID = station.StationID, DeviceType = 0, Secret = modelView.Secret, ShopID = modelView.ShopID, IsAvailable = modelView.IsAvailable, OffDate = modelView.OffDate, OnDate = modelView.OnDate, DeviceNo = modelView.DeviceNo }; DeviceRepository.Insert(device); this.DbContext.SaveChanges(); Token token = new Token { TokenID = Guid.NewGuid().ToString(), IssueTime = DateTime.Now, InvalidTime = DateTime.Now.AddYears(1000), DeviceID = device.DeviceID, Test="" }; TokenRepository.Insert(token); result=this.DbContext.Commit()>0; } catch { this.DbContext.Rollback(); } return result; }
在插入数据的时候 我们调用了 this.DbContext.SaveChanges();做临时提交,正常情况下,在commit里我们是统一提交的,但是如果在最后才提交,就获取不到自增的序列号
public class MyDbContext : DbContext, ITransaction { public MyDbContext(string connectionString) : base(connectionString) { // 是否启动延迟加载 Configuration.LazyLoadingEnabled = false; // 是否启动代理 Configuration.ProxyCreationEnabled = false; Configuration.AutoDetectChangesEnabled = false; Configuration.ValidateOnSaveEnabled = false; } public void BeginTransaction() { if (this.Database.CurrentTransaction == null) { this.Database.BeginTransaction(); } this.IsTransaction = true; } public int Commit() { int reault = this.SaveChanges(); this.IsTransaction = false; DbContextTransaction transaction = this.Database.CurrentTransaction; if (transaction != null) { transaction.Commit(); transaction.Dispose(); reault += 1; } return reault; } public void Rollback() { this.IsTransaction = false; DbContextTransaction transaction = this.Database.CurrentTransaction; if (transaction != null) { transaction.Rollback(); transaction.Dispose(); } } private bool isTransaction = false; public bool IsTransaction { get { return isTransaction; } set { this.isTransaction = value; } } }