public NestedStorageTransaction(RealStorageTransaction ambient) { if (ambient == null) { throw new ArgumentNullException(); } if (ambient.Connection == null) { throw new InvalidOperationException("No Connection"); } if (ambient.Connection.Transaction == null) { throw new InvalidOperationException("No Transaction"); } if (!(ambient.Connection.Transaction is SqlTransaction)) { throw new NotSupportedException("Sql Server Only"); } this.ambient = ambient; this.name = Convert.ToBase64String(Guid.NewGuid().ToByteArray()); (this.ambient.Connection.Transaction as SqlTransaction).Save(this.name); }
/// <summary> /// 开始事务. 请务必使用using, 如using(var t = Storage.NewTransaction()){...} /// 限同一线程及同一数据库及使用本类的方法进行的查询和操作. 若嵌套使用则整体视为一个事务. /// innerNestedTranRollbackEnabled:作为外层事务的内部嵌套事务回滚是否有效,前提是数据库为Sql Server且外部事物至少访问过一次数据库,否则抛异常 /// </summary> public static IStorageTransaction NewTransaction(bool innerNestedTranRollbackEnabled, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted) { if (currentThreadTransaction != null && !currentThreadTransaction.Disposed) { if (innerNestedTranRollbackEnabled) { if (currentThreadTransaction.Connection == null || currentThreadTransaction.Connection.Transaction == null) { throw new InvalidOperationException("outer transaction should visit database once at least"); } if (!(currentThreadTransaction.Connection.Transaction is SqlTransaction)) { throw new NotSupportedException("SQL Server Only"); } return(new NestedStorageTransaction(currentThreadTransaction)); } return(EmptyStorageTransaction.Instance); } return(currentThreadTransaction = new RealStorageTransaction(isolationLevel)); }