コード例 #1
0
        private void SetAmbientScope(DbContextScope newAmbientScope)
        {
            if (newAmbientScope == null)
            {
                throw new ArgumentNullException("newAmbientScope");
            }

            var current = CallContext.LogicalGetData(AmbientDbContextScopeKey) as InstanceIdentifier;

            if (current == newAmbientScope.instanceIdentifier)
            {
                return;
            }

            // Store the new scope's instance identifier in the CallContext, making it the ambient scope
            CallContext.LogicalSetData(AmbientDbContextScopeKey, newAmbientScope.instanceIdentifier);

            // Keep track of this instance (or do nothing if we're already tracking it)
            DbContextScopeInstances.GetValue(newAmbientScope.instanceIdentifier, key => newAmbientScope);
        }
コード例 #2
0
        /// <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.");
            }
        }
コード例 #3
0
        public TDbContext Get <TDbContext>() where TDbContext : DbContext
        {
            var ambientScope = DbContextScope.GetAmbientScope();

            return(ambientScope == null ? null : ambientScope.DbContext.Get <TDbContext>());
        }