public DbContext CreateDbContext <TDbContext>(string connectionString, IDbContextResolver dbContextResolver) where TDbContext : DbContext
        {
            DbContext dbContext = null;

            var activeTransaction = ActiveTransactions.GetOrDefault(connectionString);

            if (activeTransaction == null)
            {
                dbContext = dbContextResolver.Resolve <TDbContext>(connectionString);

                var dbtransaction = dbContext.Database.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);

                activeTransaction = new ActiveTransactionInfo(dbtransaction, dbContext);

                ActiveTransactions[connectionString] = activeTransaction;
            }
            else
            {
                dbContext = dbContextResolver.Resolve <TDbContext>(activeTransaction.DbContextTransaction.UnderlyingTransaction.Connection, false);
                dbContext.Database.UseTransaction(activeTransaction.DbContextTransaction.UnderlyingTransaction);
                activeTransaction.AttendedDbContexts.Add(dbContext);
            }

            return(dbContext);
        }
        public DbContext CreateDbContext <TDbContext>(IDbContextResolver dbContextResolver) where TDbContext : DbContext
        {
            DbContext dbContext;

            if (ActiveTransactions.TryGetValue(typeof(TDbContext), out ActiveTransaction activeTransaction) == false)
            {
                dbContext = dbContextResolver.Resolve <TDbContext>(null);

                var dbtransaction = dbContext.Database.BeginTransaction((Options.IsolationLevel ?? IsolationLevel.ReadUncommitted).ToSystemDataIsolationLevel());
                activeTransaction = new ActiveTransaction(dbtransaction, dbContext);
                ActiveTransactions[typeof(DbContext)] = activeTransaction;
            }
            else
            {
                dbContext = dbContextResolver.Resolve <TDbContext>(activeTransaction.DbContextTransaction.GetDbTransaction().Connection);

                if (dbContext.HasRelationalTransactionManager())
                {
                    dbContext.Database.UseTransaction(activeTransaction.DbContextTransaction.GetDbTransaction());
                }
                else
                {
                    dbContext.Database.BeginTransaction();
                }

                activeTransaction.AttendedDbContexts.Add(dbContext);
            }

            return(dbContext);
        }
        public DbContext CreateDbContext <TDbContext>(string connectionString, IDbContextResolver dbContextResolver) where TDbContext : DbContext
        {
            DbContext dbContext;

            var activeTransaction = ActiveTransactions.GetOrDefault(connectionString);

            if (activeTransaction == null)
            {
                dbContext = dbContextResolver.Resolve <TDbContext>(connectionString, null);

                var dbtransaction = dbContext.Database.BeginTransaction((Options.IsolationLevel ?? IsolationLevel.ReadUncommitted).ToSystemDataIsolationLevel());
                activeTransaction = new ActiveTransactionInfo(dbtransaction, dbContext);
                ActiveTransactions[connectionString] = activeTransaction;
            }
            else
            {
                dbContext = dbContextResolver.Resolve <TDbContext>(
                    connectionString,
                    activeTransaction.DbContextTransaction.GetDbTransaction().Connection
                    );

                if (dbContext.HasRelationalTransactionManager())
                {
                    dbContext.Database.UseTransaction(activeTransaction.DbContextTransaction.GetDbTransaction());
                }
                else
                {
                    dbContext.Database.BeginTransaction();
                }

                activeTransaction.AttendedDbContexts.Add(dbContext);
            }

            return(dbContext);
        }
Esempio n. 4
0
        /// <summary>
        /// 获取指定数据上下文类型<typeparamref name="TEntity"/>的实例
        /// </summary>
        /// <typeparam name="TEntity">实体类型</typeparam>
        /// <typeparam name="TKey">实体主键类型</typeparam>
        /// <returns><typeparamref name="TEntity"/>所属上下文类的实例</returns>
        public IDbContext GetDbContext <TEntity, TKey>() where TEntity : IEntity <TKey> where TKey : IEquatable <TKey>
        {
            IEntityConfigurationTypeFinder typeFinder = _serviceProvider.GetService <IEntityConfigurationTypeFinder>();
            Type entityType    = typeof(TEntity);
            Type dbContextType = typeFinder.GetDbContextTypeForEntity(entityType);

            DbContext dbContext;
            OSharpDbContextOptions  dbContextOptions = GetDbContextResolveOptions(dbContextType);
            DbContextResolveOptions resolveOptions   = new DbContextResolveOptions(dbContextOptions);
            IDbContextResolver      contextResolver  = _serviceProvider.GetService <IDbContextResolver>();
            ActiveTransactionInfo   transInfo        = ActiveTransactionInfos.GetOrDefault(resolveOptions.ConnectionString);

            //连接字符串的事务不存在,添加起始上下文事务信息
            if (transInfo == null)
            {
                resolveOptions.ExistingConnection = null;
                dbContext = contextResolver.Resolve(resolveOptions);
                RelationalDatabaseCreator dbCreator;
                if ((dbCreator = dbContext.GetService <IDatabaseCreator>() as RelationalDatabaseCreator) != null)
                {
                    if (!dbCreator.Exists())
                    {
                        throw new OsharpException($"数据上下文“{dbContext.GetType().FullName}”的数据库不存在,请通过 Migration 功能进行数据迁移创建数据库。");
                    }
                }
                IDbContextTransaction transaction = dbContext.Database.BeginTransaction();
                transInfo = new ActiveTransactionInfo(transaction, dbContext);
                ActiveTransactionInfos[resolveOptions.ConnectionString] = transInfo;
            }
            else
            {
                resolveOptions.ExistingConnection = transInfo.DbContextTransaction.GetDbTransaction().Connection;
                //相同连接串相同上下文类型并且已存在对象,直接返回上下文对象
                if (transInfo.StarterDbContext.GetType() == resolveOptions.DbContextType)
                {
                    return(transInfo.StarterDbContext as IDbContext);
                }
                dbContext = contextResolver.Resolve(resolveOptions);
                if (dbContext.IsRelationalTransaction())
                {
                    dbContext.Database.UseTransaction(transInfo.DbContextTransaction.GetDbTransaction());
                }
                else
                {
                    dbContext.Database.BeginTransaction();
                }
                transInfo.AttendedDbContexts.Add(dbContext);
            }
            return(dbContext as IDbContext);
        }
Esempio n. 5
0
        public override DbContext CreateDbContext <TDbContext>(string connectionString, IDbContextResolver dbContextResolver, string moduleName)
        {
            //var dtx = base.CreateDbContext<TDbContext>(connectionString, dbContextResolver, moduleName);

            //var currentIsolation = (IsolationLevel)SafeConvert.ToEnum(typeof(IsolationLevel), (object)Options.IsolationLevel, IsolationLevel.ReadUncommitted);
            //if (Options.IsTransactional == true && isBeginTransaction)
            //{
            //    dataBaseTransactions.Add(new DataBaseTransaction()
            //    {
            //        Transaction = dtx.Database.BeginTransaction(currentIsolation),
            //        dbContext = dtx,
            //        isCommit = false
            //    });
            //}
            //return dtx;
            DbContext dbContext;

            var activeTransaction = ActiveTransactions.GetOrDefault(connectionString);

            if (activeTransaction == null)
            {
                dbContext = dbContextResolver.Resolve <TDbContext>(connectionString, moduleName);

                var dbtransaction = dbContext.Database.BeginTransaction((Options.IsolationLevel ?? IsolationLevel.ReadCommitted).ToSystemDataIsolationLevel());
                activeTransaction = new ActiveTransactionInfo(dbtransaction, dbContext);
                ActiveTransactions[connectionString] = activeTransaction;
            }
            else
            {
                dbContext = dbContextResolver.Resolve <TDbContext>(
                    activeTransaction.DbContextTransaction.GetDbTransaction().Connection,
                    moduleName,
                    true
                    );

                if (dbContext.HasRelationalTransactionManager())
                {
                    dbContext.Database.UseTransaction(activeTransaction.DbContextTransaction.GetDbTransaction());
                }
                else
                {
                    dbContext.Database.BeginTransaction();
                }

                activeTransaction.AttendedDbContexts.Add(dbContext);
            }

            return(dbContext);
        }
Esempio n. 6
0
        protected virtual void CreateOrMigrate(CodeZeroTenantBase tenant, Action <TDbContext> seedAction)
        {
            var args = new DbPerTenantConnectionStringResolveArgs(
                tenant == null ? (int?)null : (int?)tenant.Id,
                tenant == null ? MultiTenancySides.Host : MultiTenancySides.Tenant
                );

            args["DbContextType"]         = typeof(TDbContext);
            args["DbContextConcreteType"] = typeof(TDbContext);

            var nameOrConnectionString = ConnectionStringHelper.GetConnectionString(
                _connectionStringResolver.GetNameOrConnectionString(args)
                );

            using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.Suppress))
            {
                using (var dbContext = _dbContextResolver.Resolve <TDbContext>(nameOrConnectionString, null))
                {
                    dbContext.Database.Migrate();
                    seedAction?.Invoke(dbContext);
                    _unitOfWorkManager.Current.SaveChanges();
                    uow.Complete();
                }
            }
        }
        public virtual TDbContext GetOrCreateDbContext <TDbContext>() where TDbContext : DbContext
        {
            var dbContextType = typeof(TDbContext);

            var dbContextKey = dbContextType.FullName;

            if (!ActiveDbContexts.TryGetValue(dbContextKey, out DbContext dbContext))
            {
                if (Options.IsTransactional == true)
                {
                    dbContext = _transactionStrategy.CreateDbContext <TDbContext>(_dbContextResolver);
                }
                else
                {
                    dbContext = _dbContextResolver.Resolve <TDbContext>(null);
                }

                if (Options.Timeout.HasValue && dbContext.Database.IsRelational() && !dbContext.Database.GetCommandTimeout().HasValue)
                {
                    dbContext.Database.SetCommandTimeout(Options.Timeout.Value.TotalSeconds.To <int>());
                }

                ActiveDbContexts[dbContextKey] = dbContext;
            }

            return((TDbContext)dbContext);
        }
Esempio n. 8
0
        /// <summary>
        /// 获取或创建数据库上下文
        /// </summary>
        /// <typeparam name="TDbContext">数据库上下文对象</typeparam>
        /// <param name="multiTenancySide">多租户双方中的一方</param>
        /// <returns>数据库上下文对象</returns>
        public virtual TDbContext GetOrCreateDbContext <TDbContext>(MultiTenancySides?multiTenancySide = null)
            where TDbContext : DbContext
        {
            var concreteDbContextType = _dbContextTypeMatcher.GetConcreteType(typeof(TDbContext));

            var connectionStringResolveArgs = new ConnectionStringResolveArgs(multiTenancySide);

            connectionStringResolveArgs["DbContextType"]         = typeof(TDbContext);
            connectionStringResolveArgs["DbContextConcreteType"] = concreteDbContextType;
            var connectionString = ResolveConnectionString(connectionStringResolveArgs);

            var dbContextKey = concreteDbContextType.FullName + "#" + connectionString;

            DbContext dbContext;

            if (!ActiveDbContexts.TryGetValue(dbContextKey, out dbContext))
            {
                dbContext = _dbContextResolver.Resolve <TDbContext>(connectionString);

                ((IObjectContextAdapter)dbContext).ObjectContext.ObjectMaterialized += (sender, args) =>
                {
                    ObjectContext_ObjectMaterialized(dbContext, args);
                };

                FilterExecuter.As <IEfUnitOfWorkFilterExecuter>().ApplyCurrentFilters(this, dbContext);

                ActiveDbContexts[dbContextKey] = dbContext;
            }

            return((TDbContext)dbContext);
        }
Esempio n. 9
0
        public virtual TDbContext GetOrCreateDbContext <TDbContext>() where TDbContext : DbContext
        {
            var connectionString = _connectionStringResolver.GetNameOrConnectionString(_siteId);
            var dbContextKey     = typeof(TDbContext).FullName + "#" + connectionString;

            DbContext dbContext;

            if (!_activeDbContexts.TryGetValue(dbContextKey, out dbContext))
            {
                if (Options.IsTransactional)
                {
                    dbContext = _transactionStrategy.CreateDbContext <TDbContext>(connectionString);
                }
                else
                {
                    dbContext = _dbContextResolver.Resolve <TDbContext>(connectionString);
                }

                if (Options.Timeout.HasValue && !dbContext.Database.CommandTimeout.HasValue)
                {
                    dbContext.Database.CommandTimeout = (int)Convert.ChangeType(Options.Timeout.Value.TotalSeconds, typeof(int));
                }

                ((IObjectContextAdapter)dbContext).ObjectContext.ObjectMaterialized += (sender, args) =>
                {
                    ObjectContext_ObjectMaterialized(dbContext, args);
                };

                _activeDbContexts[dbContextKey] = dbContext;
            }
            return((TDbContext)dbContext);
        }
Esempio n. 10
0
        public async Task <DbContext> CreateDbContextAsync <TDbContext>(string connectionString, IDbContextResolver dbContextResolver) where TDbContext : DbContext
        {
            var dbContext = dbContextResolver.Resolve <TDbContext>(connectionString);

            DbContexts.Add(dbContext);
            return(await Task.FromResult(dbContext));
        }
Esempio n. 11
0
        public virtual TDbContext GetOrCreateDbContext <TDbContext>()
            where TDbContext : DbContext
        {
            Type concreteDbContextType = _dbContextTypeMatcher.GetConcreteType(typeof(TDbContext));

            var connectionStringResolveArgs = new ConnectionStringResolveArgs();

            connectionStringResolveArgs["DbContextType"]         = typeof(TDbContext);
            connectionStringResolveArgs["DbContextConcreteType"] = concreteDbContextType;
            string connectionString = ResolveConnectionString(connectionStringResolveArgs);

            string dbContextKey = concreteDbContextType.FullName + "#" + connectionString;

            DbContext dbContext;

            if (!ActiveDbContexts.TryGetValue(dbContextKey, out dbContext))
            {
                if (Options.IsTransactional == true)
                {
                    dbContext = _transactionStrategy.CreateDbContext <TDbContext>(connectionString, _dbContextResolver);
                }
                else
                {
                    dbContext = _dbContextResolver.Resolve <TDbContext>(connectionString);
                }

                ((IObjectContextAdapter)dbContext).ObjectContext.ObjectMaterialized += (sender, args) => { ObjectContext_ObjectMaterialized(dbContext, args); };

                FilterExecuter.As <IEfUnitOfWorkFilterExecuter>().ApplyCurrentFilters(this, dbContext);

                ActiveDbContexts[dbContextKey] = dbContext;
            }

            return((TDbContext)dbContext);
        }
Esempio n. 12
0
        /// <summary>
        /// 获取指定数据上下文类型<typeparamref name="TEntity"/>的实例,并将同数据库连接字符串的上下文实例进行分组归类
        /// </summary>
        /// <typeparam name="TEntity">实体类型</typeparam>
        /// <typeparam name="TKey">实体主键类型</typeparam>
        /// <returns><typeparamref name="TEntity"/>所属上下文类的实例</returns>
        public IDbContext GetDbContext <TEntity, TKey>() where TEntity : IEntity <TKey> where TKey : IEquatable <TKey>
        {
            IEntityConfigurationTypeFinder typeFinder = _serviceProvider.GetService <IEntityConfigurationTypeFinder>();
            Type entityType    = typeof(TEntity);
            Type dbContextType = typeFinder.GetDbContextTypeForEntity(entityType);
            OSharpDbContextOptions  dbContextOptions = GetDbContextResolveOptions(dbContextType);
            DbContextResolveOptions resolveOptions   = new DbContextResolveOptions(dbContextOptions);

            //已存在上下文对象,直接返回
            DbContextBase dbContext = _dbContextMamager.Get(dbContextType, resolveOptions.ConnectionString);

            if (dbContext != null)
            {
                return(dbContext);
            }
            IDbContextResolver contextResolver = _serviceProvider.GetService <IDbContextResolver>();

            dbContext = (DbContextBase)contextResolver.Resolve(resolveOptions);
            if (!dbContext.ExistsRelationalDatabase())
            {
                throw new OsharpException($"数据上下文“{dbContext.GetType().FullName}”的数据库不存在,请通过 Migration 功能进行数据迁移创建数据库。");
            }
            if (resolveOptions.ExistingConnection == null)
            {
                resolveOptions.ExistingConnection = dbContext.Database.GetDbConnection();
            }
            _dbContextMamager.Add(dbContextOptions.ConnectionString, dbContext);

            return(dbContext);
        }
Esempio n. 13
0
        /// <summary>
        /// 获取指定数据实体的上下文类型
        /// </summary>
        /// <param name="entityType">实体类型</param>
        /// <returns>实体所属上下文实例</returns>
        public IDbContext GetDbContext(Type entityType)
        {
            if (!entityType.IsEntityType())
            {
                throw new OsharpException($"类型“{entityType}”不是实体类型");
            }

            IEntityConfigurationTypeFinder typeFinder = _serviceProvider.GetService <IEntityConfigurationTypeFinder>();
            Type dbContextType = typeFinder.GetDbContextTypeForEntity(entityType);

            //已存在上下文对象,直接返回
            DbContextBase dbContext = _dbContexts.FirstOrDefault(m => m.GetType() == dbContextType);

            if (dbContext != null)
            {
                return(dbContext);
            }
            IDbContextResolver contextResolver = _serviceProvider.GetService <IDbContextResolver>();

            dbContext = (DbContextBase)contextResolver.Resolve(_resolveOptions);
            if (!dbContext.ExistsRelationalDatabase())
            {
                throw new OsharpException($"数据上下文“{dbContext.GetType().FullName}”的数据库不存在,请通过 Migration 功能进行数据迁移创建数据库。");
            }
            if (_resolveOptions.ExistingConnection == null)
            {
                _resolveOptions.ExistingConnection = dbContext.Database.GetDbConnection();
            }

            dbContext.UnitOfWork = this;
            _dbContexts.Add(dbContext);

            return(dbContext);
        }
        public virtual TDbContext GetOrCreateDbContext <TDbContext>(MultiTenancySides?multiTenancySide = null)
            where TDbContext : DbContext
        {
            var concreteDbContextType = _dbContextTypeMatcher.GetConcreteType(typeof(TDbContext));

            var connectionStringResolveArgs = new ConnectionStringResolveArgs(multiTenancySide);

            connectionStringResolveArgs["DbContextType"]         = typeof(TDbContext);
            connectionStringResolveArgs["DbContextConcreteType"] = concreteDbContextType;
            var connectionString = ResolveConnectionString(connectionStringResolveArgs);

            var dbContextKey = concreteDbContextType.FullName + "#" + connectionString;

            DbContext dbContext;

            if (!ActiveDbContexts.TryGetValue(dbContextKey, out dbContext))
            {
                dbContext = _dbContextResolver.Resolve <TDbContext>(connectionString);

                //TODO: Object materialize event
                //TODO: Apply current filters to this dbcontext

                if (Options.IsTransactional == true)
                {
                    BeginTransaction(dbContext);
                }

                ActiveDbContexts[dbContextKey] = dbContext;
            }

            return((TDbContext)dbContext);
        }
Esempio n. 15
0
        public virtual TDbContext GetOrCreateDbContext <TDbContext>(MultiTenancySides?multiTenancySide = null,
                                                                    string name = null)
            where TDbContext : DbContext
        {
            var concreteDbContextType = _dbContextTypeMatcher.GetConcreteType(typeof(TDbContext));

            var connectionStringResolveArgs = new ConnectionStringResolveArgs(multiTenancySide)
            {
                ["DbContextType"]         = typeof(TDbContext),
                ["DbContextConcreteType"] = concreteDbContextType
            };

            var connectionString = ResolveConnectionString(connectionStringResolveArgs);

            var dbContextKey = concreteDbContextType.FullName + "#" + connectionString;

            if (name != null)
            {
                dbContextKey += "#" + name;
            }

            if (ActiveDbContexts.TryGetValue(dbContextKey, out var dbContext))
            {
                return((TDbContext)dbContext);
            }

            if (Options.IsTransactional == true)
            {
                dbContext = _transactionStrategy.CreateDbContext <TDbContext>(connectionString, _dbContextResolver);
            }
            else
            {
                dbContext = _dbContextResolver.Resolve <TDbContext>(connectionString);
            }

            if (dbContext is IShouldInitializeDcontext abpDbContext)
            {
                abpDbContext.Initialize(new AbpEfDbContextInitializationContext(this));
            }

            FilterExecuter.As <IEfUnitOfWorkFilterExecuter>().ApplyCurrentFilters(this, dbContext);

            ActiveDbContexts[dbContextKey] = dbContext;

            return((TDbContext)dbContext);
        }
Esempio n. 16
0
        public DbContext CreateDbContext <TDbContext>(string connectionString, IDbContextResolver dbContextResolver)
            where TDbContext : DbContext
        {
            var dbContext = dbContextResolver.Resolve <TDbContext>(connectionString);

            DbContexts.Add(dbContext);
            return(dbContext);
        }
        public virtual DbContext CreateDbContext <TDbContext>(string connectionString, IDbContextResolver dbContextResolver, string moduleName)
            where TDbContext : DbContext
        {
            var dbContext = dbContextResolver.Resolve <TDbContext>(connectionString, moduleName);

            DbContexts.Add(dbContext);
            return(dbContext);
        }
Esempio n. 18
0
        public virtual async Task <TDbContext> GetOrCreateDbContextAsync <TDbContext>(
            MultiTenancySides?multiTenancySide = null, string name = null)
            where TDbContext : DbContext
        {
            var concreteDbContextType = _dbContextTypeMatcher.GetConcreteType(typeof(TDbContext));

            var connectionStringResolveArgs = new ConnectionStringResolveArgs(multiTenancySide)
            {
                ["DbContextType"]         = typeof(TDbContext),
                ["DbContextConcreteType"] = concreteDbContextType
            };

            var connectionString = await ResolveConnectionStringAsync(connectionStringResolveArgs);

            var dbContextKey = concreteDbContextType.FullName + "#" + connectionString;

            if (name != null)
            {
                dbContextKey += "#" + name;
            }

            if (ActiveDbContexts.TryGetValue(dbContextKey, out var dbContext))
            {
                return((TDbContext)dbContext);
            }

            if (Options.IsTransactional == true)
            {
                dbContext = await _transactionStrategy
                            .CreateDbContextAsync <TDbContext>(connectionString, _dbContextResolver);
            }
            else
            {
                dbContext = _dbContextResolver.Resolve <TDbContext>(connectionString, null);
            }

            if (dbContext is IShouldInitializeDcontext abpDbContext)
            {
                abpDbContext.Initialize(new AbpEfDbContextInitializationContext(this));
            }

            ActiveDbContexts[dbContextKey] = dbContext;

            return((TDbContext)dbContext);
        }
Esempio n. 19
0
        public DbContext CreateDbContext <TDbContext>(string connectionString, IDbContextResolver dbContextResolver) where TDbContext : DbContext
        {
            EnsureCurrentTransactionInitialized();

            var dbContext = dbContextResolver.Resolve <TDbContext>(connectionString);

            DbContexts.Add(dbContext);
            return(dbContext);
        }
        public virtual TDbContext GetOrCreateDbContext <TDbContext>(MultiTenancySides?multiTenancySide = null)
            where TDbContext : DbContext
        {
            var concreteDbContextType = _dbContextTypeMatcher.GetConcreteType(typeof(TDbContext));

            var connectionStringResolveArgs = new ConnectionStringResolveArgs(multiTenancySide);

            connectionStringResolveArgs["DbContextType"]         = typeof(TDbContext);
            connectionStringResolveArgs["DbContextConcreteType"] = concreteDbContextType;
            var connectionString = ResolveConnectionString(connectionStringResolveArgs);

            var dbContextKey = concreteDbContextType.FullName + "#" + connectionString;

            DbContext dbContext;

            if (!ActiveDbContexts.TryGetValue(dbContextKey, out dbContext))
            {
                dbContext = _dbContextResolver.Resolve <TDbContext>(connectionString);
                //((IObjectContextAdapter)dbContext).ObjectContext.ObjectMaterialized += (sender, args) =>
                //{
                //    ObjectContext_ObjectMaterialized(dbContext, args);
                //};

                //foreach (var filter in Filters)
                //{
                //    if (filter.IsEnabled)
                //    {
                //        dbContext.EnableFilter(filter.FilterName);
                //    }
                //    else
                //    {
                //        dbContext.DisableFilter(filter.FilterName);
                //    }

                //    foreach (var filterParameter in filter.FilterParameters)
                //    {
                //        if (TypeHelper.IsFunc<object>(filterParameter.Value))
                //        {
                //            dbContext.SetFilterScopedParameterValue(filter.FilterName, filterParameter.Key, (Func<object>)filterParameter.Value);
                //        }
                //        else
                //        {
                //            dbContext.SetFilterScopedParameterValue(filter.FilterName, filterParameter.Key, filterParameter.Value);
                //        }
                //    }
                //}

                if (Options.IsTransactional == true)
                {
                    BeginTransaction(dbContext);
                }

                ActiveDbContexts[dbContextKey] = dbContext;
            }

            return((TDbContext)dbContext);
        }
Esempio n. 21
0
        public DbContext CreateDbContext <TDbContext>(string nameOrConnectionString)
            where TDbContext : DbContext
        {
            IDbContextResolver dbContextResolver = _dependencyResolver.Resolve <IDbContextResolver>();
            var dbContext = dbContextResolver.Resolve <TDbContext>(nameOrConnectionString);

            DbContexts.Add(dbContext);
            return(dbContext);
        }
        public static IDbContext Create(DbContextOption option)
        {
            //if (option.DbContextType != null)
            //{
            //    return (IDbContext)ObjectHelper.CreateInstance(option.DbContextType, new object[] { option.IOMode, option.ConnectionStringName });
            //}
            IDbContextResolver resolver = IoC.Container.Resolve <IDbContextResolver>();

            return(resolver.Resolve(option));
        }
Esempio n. 23
0
        public TDbContext GetDbContext <TDbContext>()
            where TDbContext : DbContext
        {
            var connectionStringResolveArgs = new ConnectionStringResolveArgs() //MultiTenancySides
            {
                ["DbContextType"] = typeof(TDbContext)
            };
            var connectionString = _connectionStringResolver.GetNameOrConnectionString(connectionStringResolveArgs);

            return(_dbContextResolver.Resolve <TDbContext>(connectionString, null));
        }
Esempio n. 24
0
        public virtual TDbContext GetOrCreateDbContext <TDbContext>()
            where TDbContext : DbContext
        {
            //todo: 区分oracle和sqlserver数据库

            //var connectionString = "DefaultConnection";

            var concreteDbContextType = _dbContextTypeMatcher.GetConcreteType(typeof(TDbContext));

            string connectionString;
            string schema = null;

            if (DbConnectionHelper.DbCatagory == DBType.Oracle.ToString())
            {
                connectionString = ResolveConnectionString(ref schema);
                connectionString = "Oracle";
            }
            else
            {
                connectionString = ResolveConnectionString();
            }
            var dbContextKey = concreteDbContextType.FullName + "#" + connectionString;

            DbContext dbContext;

            if (!ActiveDbContexts.TryGetValue(dbContextKey, out dbContext))
            {
                if (Options.IsTransactional == true)
                {
                    //解析出来的是TransactionScopeEfTransactionStrategy
                    dbContext = _transactionStrategy.CreateDbContext <TDbContext>(connectionString, _dbContextResolver, schema);
                }
                else
                {
                    dbContext = _dbContextResolver.Resolve <TDbContext>(connectionString);
                }

                DbContexts.Add(dbContext);

                //if (Options.Timeout.HasValue && !dbContext.Database.CommandTimeout.HasValue)
                //{
                //    dbContext.Database.CommandTimeout = Options.Timeout.Value.TotalSeconds.To<int>();
                //}

                ((IObjectContextAdapter)dbContext).ObjectContext.ObjectMaterialized += (sender, args) =>
                {
                    ObjectContext_ObjectMaterialized(dbContext, args);
                };

                ActiveDbContexts[dbContextKey] = dbContext;
            }

            return((TDbContext)dbContext);
        }
        public virtual DbContext CreateDbContext(string connectionString, IDbContextResolver dbContextResolver, string dbContextProviderName)
        {
            DbContext dbContext;

            var activeTransaction = ActiveTransactions.GetOrDefault(connectionString);

            if (activeTransaction == null)
            {
                dbContext = dbContextResolver.Resolve(connectionString, null, this.Options, dbContextProviderName);

                // 缓存模型
                _contextModelStorage.AddOrUpdate(connectionString, dbContext.Model);


                var dbtransaction = dbContext.Database.BeginTransaction((Options.IsolationLevel ?? IsolationLevel.ReadUncommitted).ToSystemDataIsolationLevel());
                activeTransaction = new ActiveTransactionInfo(dbtransaction, dbContext);
                ActiveTransactions[connectionString] = activeTransaction;
            }
            else
            {
                dbContext = dbContextResolver.Resolve(
                    connectionString,
                    activeTransaction.DbContextTransaction.GetDbTransaction().Connection,
                    this.Options,
                    dbContextProviderName
                    );

                if (dbContext.HasRelationalTransactionManager())
                {
                    dbContext.Database.UseTransaction(activeTransaction.DbContextTransaction.GetDbTransaction());
                }
                else
                {
                    dbContext.Database.BeginTransaction();
                }

                activeTransaction.AttendedDbContexts.Add(dbContext);
            }

            return(dbContext);
        }
        public Task <DbContext> CreateDbContextAsync <TDbContext>(string connectionString, IDbContextResolver dbContextResolver) where TDbContext : DbContext
        {
            DbContext dbContext;

            var activeTransaction = ActiveTransactions.GetOrDefault(connectionString);

            if (activeTransaction == null)
            {
                dbContext = dbContextResolver.Resolve <TDbContext>(connectionString);
                var dbTransaction = dbContext.Database.BeginTransaction((Options.IsolationLevel ?? IsolationLevel.ReadUncommitted).ToSystemDataIsolationLevel());
                activeTransaction = new ActiveTransactionInfo(dbTransaction, dbContext);
                ActiveTransactions[connectionString] = activeTransaction;
            }
            else
            {
                dbContext = dbContextResolver.Resolve <TDbContext>(activeTransaction.DbContextTransaction.UnderlyingTransaction.Connection, false);
                dbContext.Database.UseTransaction(activeTransaction.DbContextTransaction.UnderlyingTransaction);
                activeTransaction.AttendedDbContexts.Add(dbContext);
            }

            return(Task.FromResult(dbContext));
        }
Esempio n. 27
0
        public virtual TDbContext GetOrCreateDbContext <TDbContext>(MultiTenancySides?multiTenancySide = null, string name = null)
            where TDbContext : DbContext
        {
            var concreteDbContextType = _dbContextTypeMatcher.GetConcreteType(typeof(TDbContext));

            var connectionStringResolveArgs = new ConnectionStringResolveArgs(multiTenancySide);

            connectionStringResolveArgs["DbContextType"]         = typeof(TDbContext);
            connectionStringResolveArgs["DbContextConcreteType"] = concreteDbContextType;
            var connectionString = ResolveConnectionString(connectionStringResolveArgs);

            var dbContextKey = concreteDbContextType.FullName + "#" + connectionString;

            if (name != null)
            {
                dbContextKey += "#" + name;
            }

            DbContext dbContext;

            if (!ActiveDbContexts.TryGetValue(dbContextKey, out dbContext))
            {
                if (Options.IsTransactional == true)
                {
                    dbContext = _transactionStrategy.CreateDbContext <TDbContext>(connectionString, _dbContextResolver);
                }
                else
                {
                    dbContext = _dbContextResolver.Resolve <TDbContext>(connectionString);
                }

                if (Options.Timeout.HasValue && !dbContext.Database.CommandTimeout.HasValue)
                {
                    dbContext.Database.CommandTimeout = Options.Timeout.Value.TotalSeconds.To <int>();
                }

                if (Clock.SupportsMultipleTimezone)
                {
                    ((IObjectContextAdapter)dbContext).ObjectContext.ObjectMaterialized += (sender, args) =>
                    {
                        ObjectContext_ObjectMaterialized(dbContext, args);
                    };
                }

                FilterExecuter.As <IEfUnitOfWorkFilterExecuter>().ApplyCurrentFilters(this, dbContext);

                ActiveDbContexts[dbContextKey] = dbContext;
            }

            return((TDbContext)dbContext);
        }
Esempio n. 28
0
        public virtual TDbContext GetOrCreateDbContext <TDbContext>(MultiTenancySides?multiTenancySide = null)
            where TDbContext : DbContext
        {
            var connectionStringResolveArgs = new ConnectionStringResolveArgs(multiTenancySide);

            connectionStringResolveArgs["DbContextType"] = typeof(TDbContext);
            var connectionString = ResolveConnectionString(connectionStringResolveArgs);

            var dbContextKey = typeof(TDbContext).FullName + "#" + connectionString;

            DbContext dbContext;

            if (!ActiveDbContexts.TryGetValue(dbContextKey, out dbContext))
            {
                dbContext = _dbContextResolver.Resolve <TDbContext>(connectionString);

                ((IObjectContextAdapter)dbContext).ObjectContext.ObjectMaterialized += (sender, args) =>
                {
                    ObjectContext_ObjectMaterialized(dbContext, args);
                };

                foreach (var filter in Filters)
                {
                    if (filter.IsEnabled)
                    {
                        dbContext.EnableFilter(filter.FilterName);
                    }
                    else
                    {
                        dbContext.DisableFilter(filter.FilterName);
                    }

                    foreach (var filterParameter in filter.FilterParameters)
                    {
                        if (TypeHelper.IsFunc <object>(filterParameter.Value))
                        {
                            dbContext.SetFilterScopedParameterValue(filter.FilterName, filterParameter.Key, (Func <object>)filterParameter.Value);
                        }
                        else
                        {
                            dbContext.SetFilterScopedParameterValue(filter.FilterName, filterParameter.Key, filterParameter.Value);
                        }
                    }
                }

                ActiveDbContexts[dbContextKey] = dbContext;
            }

            return((TDbContext)dbContext);
        }
Esempio n. 29
0
        public virtual TDbContext GetOrCreateDbContext <TDbContext, TEntity>(MultiTenancySides?multiTenancySide = null)
            where TDbContext : DbContext
        {
            var concreteDbContextType = _dbContextTypeMatcher.GetConcreteType(typeof(TDbContext));

            var connectionStringResolveArgs = new ConnectionStringResolveArgs(multiTenancySide);

            connectionStringResolveArgs["DbContextType"]         = typeof(TDbContext);
            connectionStringResolveArgs["DbContextConcreteType"] = concreteDbContextType;
            var connectionString = ResolveConnectionString(connectionStringResolveArgs);
            var entityAssemblyId = typeof(TEntity).Assembly.GetName().Name;

            if (!entityConfigurations.Any(e => string.Equals(e.EntityModule, entityAssemblyId, StringComparison.OrdinalIgnoreCase)))
            {
                throw new BlocksDBORMException(StringLocal.Format($"{entityAssemblyId} not found in EntityConfigurations."));
            }
            var moduleName   = entityAssemblyId; //extensionManager.GetExtension(typeof(TEntity).Assembly.GetName().Name).Name;
            var dbContextKey = moduleName + "#" + concreteDbContextType.FullName + "#" + connectionString;

            DbContext dbContext;

            if (!ActiveDbContexts.TryGetValue(dbContextKey, out dbContext))
            {
                if (Options.IsTransactional == true)
                {
                    dbContext = _transactionStrategy.CreateDbContext <TDbContext>(connectionString, _dbContextResolver, moduleName);
                }
                else
                {
                    dbContext = _dbContextResolver.Resolve <TDbContext>(connectionString, moduleName);
                }

                if (Options.Timeout.HasValue && !dbContext.Database.GetCommandTimeout().HasValue)
                {
                    dbContext.Database.SetCommandTimeout(SafeConvert.ToInt32(Options.Timeout.Value.TotalSeconds));
                }

                //TODO ObjectMaterialize
                //((IObjectContextAdapter)dbContext).ObjectContext.ObjectMaterialized += (sender, args) =>
                //{
                //    ObjectContext_ObjectMaterialized(dbContext, args);
                //};

                // FilterExecuter.As<IEfUnitOfWorkFilterExecuter>().ApplyCurrentFilters(this, dbContext);

                ActiveDbContexts[dbContextKey] = dbContext;
            }

            return((TDbContext)dbContext);
        }
Esempio n. 30
0
        /// <summary>
        /// 获取指定数据上下文类型<typeparamref name="TEntity"/>的实例
        /// </summary>
        /// <typeparam name="TEntity">实体类型</typeparam>
        /// <typeparam name="TKey">实体主键类型</typeparam>
        /// <returns><typeparamref name="TEntity"/>所属上下文类的实例</returns>
        public IDbContext GetDbContext <TEntity, TKey>() where TEntity : IEntity <TKey> where TKey : IEquatable <TKey>
        {
            IEntityConfigurationTypeFinder typeFinder = _serviceProvider.GetService <IEntityConfigurationTypeFinder>();
            Type dbContextType = typeFinder.GetDbContextTypeForEntity(typeof(TEntity));

            DbContext               dbContext;
            OsharpDbContextConfig   dbContextConfig = GetDbContextResolveOptionsConfig(dbContextType);
            DbContextResolveOptions resolveOptions  = new DbContextResolveOptions(dbContextConfig);
            IDbContextResolver      contextResolver = _serviceProvider.GetService <IDbContextResolver>();
            ActiveTransactionInfo   transInfo       = ActiveTransactionInfos.GetOrDefault(resolveOptions.ConnectionString);

            //连接字符串的事务不存在,添加起始上下文事务信息
            if (transInfo == null)
            {
                resolveOptions.ExistingConnection = null;
                dbContext = contextResolver.Resolve(resolveOptions);
                IDbContextTransaction transaction = dbContext.Database.BeginTransaction();
                transInfo = new ActiveTransactionInfo(transaction, dbContext);
                ActiveTransactionInfos[resolveOptions.ConnectionString] = transInfo;
            }
            else
            {
                resolveOptions.ExistingConnection = transInfo.DbContextTransaction.GetDbTransaction().Connection;
                dbContext = contextResolver.Resolve(resolveOptions);
                if (dbContext.IsRelationalTransaction())
                {
                    dbContext.Database.UseTransaction(transInfo.DbContextTransaction.GetDbTransaction());
                }
                else
                {
                    dbContext.Database.BeginTransaction();
                }
                transInfo.AttendedDbContexts.Add(dbContext);
            }
            return(dbContext as IDbContext);
        }