/// <summary> /// Dispose implementation, checking post conditions for purpose and saving. /// </summary> /// <param name="disposing">Are we disposing?</param> protected virtual void Dispose(bool disposing) { if (disposing) { // We're disposing and SaveChanges wasn't called. That usually // means we're exiting the scope with an exception. Block saves // of the entire unit of work. if (this.purpose == DbContextScopePurpose.Writing && !this.saveChangesCalled) { this.scopedDbContexts.BlockSave = true; // Don't throw here - it would mask original exception when exiting // a using block. } if (this.scopedDbContexts != null && this.isRoot) { this.scopedDbContexts.Dispose(); this.scopedDbContexts = null; } } }
/// <summary> /// Initializes a new instance of the <see cref="DbContextScope" /> class. /// </summary> /// <param name="purpose">Will this dbcontext scope be used for reading or writing?</param> /// <param name="isNewScope">Will this dbcontext scope be a new DbContextScope.</param> public DbContextScope(DbContextScopePurpose purpose, bool isNewScope = false) { this.purpose = purpose; this.parentScope = GetAmbientScope(); if (this.parentScope != null && !isNewScope) { this.scopedDbContexts = this.parentScope.DbContext; } else { this.scopedDbContexts = new DbContextCollection(purpose == DbContextScopePurpose.Writing); this.isRoot = true; } this.SetAmbientScope(this); if (purpose == DbContextScopePurpose.Writing && !this.scopedDbContexts.ForWriting) { throw new InvalidOperationException( "Can't open a child DbContextScope for writing when the root scope " + "is opened for reading."); } }