Base solution for your next web application
Open Closed

Bug for plus DbContext #2986


User avatar
0
goldstar25 created

My project is:

Base .NET Core Base directory plugin mode Multi-DbContext

Plus DbContext Code:

[DbConfigurationType(typeof(AdminDbConfiguration))]
    public class CTMSDbContext : AbpDbContext
    {
        public virtual IDbSet<Center> Centers { get; set; }

        public CTMSDbContext() : base("Default")
        {
        }

        public CTMSDbContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {

        }

        public CTMSDbContext(DbConnection existingConnection)
            : base(existingConnection, true)
        {

        }

        public CTMSDbContext(DbConnection existingConnection, bool contextOwnsConnection)
            : base(existingConnection, contextOwnsConnection)
        {

        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

        }

    }
    public class CTMSDbConfiguration : DbConfiguration
    {
        public CTMSDbConfiguration()
        {
            SetProviderServices(
                "System.EntityFramework.SqlClient",
                System.Data.Entity.SqlServer.SqlProviderServices.Instance
            );
        }
    }

    [DependsOn(
        typeof(AbpZeroEntityFrameworkModule),
        typeof(AdminCoreModule),
        typeof(AdminEntityFrameworkModule),
        typeof(CTMSCoreModule))]
    public class CTMSDataModule : AbpModule
    {
        public override void PreInitialize()
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<CTMSDbContext, Configuration>());
            //Configuration.ReplaceService(typeof(IConnectionStringResolver), () =>
            //{
            //    IocManager.IocContainer.Register(
            //        Component.For<IConnectionStringResolver, IDbPerTenantConnectionStringResolver>()
            //            .ImplementedBy<DbPerTenantConnectionStringResolver>()
            //            .LifestyleTransient()
            //        );
            //});
            ////设置连接字符串名称
            //Configuration.DefaultNameOrConnectionString = "Default";
        }
        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
        }
    }

    public class Configuration : DbMigrationsConfiguration<CTMSDbContext>
    {
        public Configuration()
        {
            ContextKey = "Magicodes.CTMS.CTMSDbContext";
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
        }

        protected override void Seed(CTMSDbContext context)
        {

        }
    }

Problem: When I deploy it to server,the AdminDbContext(base AbpZeroDbContext<Tenant, Role, User>) access database is OK,But CTMSDbContext will can't connect to the database.Detail:

ERROR 2017-04-21 11:48:20,540 [31   ] Mvc.ExceptionHandling.AbpExceptionFilter - ComponentActivator: could not instantiate Magicodes.CTMS.EntityFramework.CTMSDbContext
Castle.MicroKernel.ComponentActivator.ComponentActivatorException: ComponentActivator: could not instantiate Magicodes.CTMS.EntityFramework.CTMSDbContext ---> System.Reflection.TargetInvocationException: 调用的目标发生了异常。 ---> System.Data.SqlClient.SqlException: 在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误。未找到或无法访问服务器。请验证实例名称是否正确并且 SQL Server 已配置为允许远程连接。 (provider: SQL Network Interfaces, error: 26 - 定位指定的服务器/实例时出错)
   在 System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling)
   在 System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   在 System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   在 System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   在 System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   在 System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   在 System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   在 System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   在 System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   在 System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   在 System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
   在 System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   在 System.Data.SqlClient.SqlConnection.Open()
   在 System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<Open>b__36(DbConnection t, DbConnectionInterceptionContext c)
   在 System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   在 System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)
   在 System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass33.<UsingConnection>b__32()
   在 System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
   在 System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   在 System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
   在 System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action`1 act)
   在 System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act)
   在 System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable`1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript)
   在 System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)
   在 System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)
   在 System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase()
   在 System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection)
   在 System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   在 System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
   在 System.Data.Entity.MigrateDatabaseToLatestVersion`2.InitializeDatabase(TContext context)
   在 System.Data.Entity.Internal.InternalContext.&lt;&gt;c__DisplayClassf`1.<CreateInitializationAction>b__e()
   在 System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
   在 System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
   在 System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
   在 System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
   在 System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
   在 System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
   在 System.Data.Entity.Internal.InternalContext.ForceOSpaceLoadingForKnownEntityTypes()
   在 System.Data.Entity.DbContext.System.Data.Entity.Infrastructure.IObjectContextAdapter.get_ObjectContext()
   在 Abp.EntityFramework.AbpDbContext.RegisterToChanges()
   在 Abp.EntityFramework.AbpDbContext..ctor(String nameOrConnectionString)
   在 Magicodes.CTMS.EntityFramework.CTMSDbContext..ctor(String nameOrConnectionString)
   --- 内部异常堆栈跟踪的结尾 ---
   在 System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   在 System.Reflection.RuntimeConstructorInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   在 Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.FastCreateInstance(Type implType, Object[] arguments, ConstructorCandidate constructor)
   在 Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateInstanceCore(ConstructorCandidate constructor, Object[] arguments, Type implType)
   --- 内部异常堆栈跟踪的结尾 ---
   在 Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateInstanceCore(ConstructorCandidate constructor, Object[] arguments, Type implType)
   在 Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateInstance(CreationContext context, ConstructorCandidate constructor, Object[] arguments)
   在 Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext context)
   在 Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext context)
   在 Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext context, Burden burden)
   在 Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.CreateInstance(CreationContext context, Boolean trackedExternally)
   在 Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.Resolve(CreationContext context, IReleasePolicy releasePolicy)
   在 Castle.MicroKernel.Handlers.DefaultHandler.ResolveCore(CreationContext context, Boolean requiresDecommission, Boolean instanceRequired, Burden& burden)
   在 Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext context, Boolean instanceRequired)
   在 Castle.MicroKernel.Handlers.AbstractHandler.Resolve(CreationContext context)
   在 Castle.MicroKernel.DefaultKernel.ResolveComponent(IHandler handler, Type service, IDictionary additionalArguments, IReleasePolicy policy)
   在 Castle.MicroKernel.DefaultKernel.Castle.MicroKernel.IKernelInternal.Resolve(Type service, IDictionary arguments, IReleasePolicy policy)
   在 Castle.MicroKernel.DefaultKernel.Resolve(Type service, IDictionary arguments)
   在 Castle.Windsor.WindsorContainer.Resolve(Type service, IDictionary arguments)
   在 Castle.Windsor.WindsorContainer.Resolve(Type service, Object argumentsAsAnonymousType)
   在 Abp.Dependency.IocManager.Resolve(Type type, Object argumentsAsAnonymousType)
   在 Abp.EntityFramework.DefaultDbContextResolver.Resolve[TDbContext](String connectionString)
   在 Abp.EntityFramework.Uow.TransactionScopeEfTransactionStrategy.CreateDbContext[TDbContext](String connectionString, IDbContextResolver dbContextResolver)
   在 Abp.EntityFramework.Uow.EfUnitOfWork.GetOrCreateDbContext[TDbContext](Nullable`1 multiTenancySide)
   在 Abp.EntityFramework.Uow.UnitOfWorkExtensions.GetDbContext[TDbContext](IActiveUnitOfWork unitOfWork, Nullable`1 multiTenancySide)
   在 Abp.EntityFramework.Uow.UnitOfWorkDbContextProvider`1.GetDbContext(Nullable`1 multiTenancySide)
   在 Castle.Proxies.EfRepositoryBase`3Proxy_22.get_Context_callback()
   在 Castle.Proxies.Invocations.EfRepositoryBase`3_get_Context_26.InvokeMethodOnTarget()
   在 Castle.DynamicProxy.AbstractInvocation.Proceed()
   在 Abp.Domain.Uow.UnitOfWorkInterceptor.PerformSyncUow(IInvocation invocation, UnitOfWorkOptions options)
   在 Abp.Domain.Uow.UnitOfWorkInterceptor.PerformUow(IInvocation invocation, UnitOfWorkOptions options)
   在 Abp.Domain.Uow.UnitOfWorkInterceptor.Intercept(IInvocation invocation)
   在 Castle.DynamicProxy.AbstractInvocation.Proceed()
   在 Castle.Proxies.EfRepositoryBase`3Proxy_22.get_Context()
   在 Abp.EntityFramework.Repositories.EfRepositoryBase`3.get_Table()
   在 Castle.Proxies.EfRepositoryBase`3Proxy_22.get_Table_callback()
   在 Castle.Proxies.Invocations.EfRepositoryBase`3_get_Table_26.InvokeMethodOnTarget()
   在 Castle.DynamicProxy.AbstractInvocation.Proceed()
   在 Abp.Domain.Uow.UnitOfWorkInterceptor.PerformSyncUow(IInvocation invocation, UnitOfWorkOptions options)
   在 Abp.Domain.Uow.UnitOfWorkInterceptor.PerformUow(IInvocation invocation, UnitOfWorkOptions options)
   在 Abp.Domain.Uow.UnitOfWorkInterceptor.Intercept(IInvocation invocation)
   在 Castle.DynamicProxy.AbstractInvocation.Proceed()
   在 Castle.Proxies.EfRepositoryBase`3Proxy_22.get_Table()
   在 Castle.Proxies.EfRepositoryBase`3Proxy_22.GetAll_callback()
   在 Castle.Proxies.Invocations.EfRepositoryBase`3_GetAll_26.InvokeMethodOnTarget()
   在 Castle.DynamicProxy.AbstractInvocation.Proceed()
   在 Abp.Domain.Uow.UnitOfWorkInterceptor.PerformSyncUow(IInvocation invocation, UnitOfWorkOptions options)
   在 Abp.Domain.Uow.UnitOfWorkInterceptor.PerformUow(IInvocation invocation, UnitOfWorkOptions options)
   在 Abp.Domain.Uow.UnitOfWorkInterceptor.Intercept(IInvocation invocation)
   在 Castle.DynamicProxy.AbstractInvocation.Proceed()
   在 Castle.Proxies.EfRepositoryBase`3Proxy_22.GetAll()
   在 Magicodes.CTMS.Project.CenterAppService.CreateCentersQuery(GetCentersInput input)
   在 Magicodes.CTMS.Project.CenterAppService.<GetCenters>d__2.MoveNext()
--- 引发异常的上一位置中堆栈跟踪的末尾 ---
   在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   在 Microsoft.AspNetCore.Mvc.Internal.ObjectMethodExecutor.<CastToObject>d__40`1.MoveNext()
--- 引发异常的上一位置中堆栈跟踪的末尾 ---
   在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   在 System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   在 Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.&lt;InvokeActionMethodAsync&gt;d__27.MoveNext()
--- 引发异常的上一位置中堆栈跟踪的末尾 ---
   在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   在 Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.&lt;InvokeNextActionFilterAsync&gt;d__25.MoveNext()
--- 引发异常的上一位置中堆栈跟踪的末尾 ---
   在 Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
   在 Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   在 Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.&lt;InvokeNextExceptionFilterAsync&gt;d__24.MoveNext()

9 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    Does it work on your local environment ?

    Thanks.

  • User Avatar
    0
    goldstar25 created

    Yes.It's works on my computer,but not works on server.

  • User Avatar
    0
    goldstar25 created

    Have you tried it? Fix a point,The CTMSDbContext works on these code on my local computer:

    public CTMSDbContext() : base(GetConnectionString())
            {
            }
            private static string GetConnectionString()
            {
                //Notice that; this logic only works on development time.
                //It is used to get connection string from appsettings.json in the Web project.
    
                var configuration = AppConfigurations.Get(
                    WebContentDirectoryFinder.CalculateContentRootFolder()
                    );
    
                return configuration.GetConnectionString(
                    AdminConsts.ConnectionStringName
                    );
            }
    

    I read the source,it should be not works on server. I tried a lot of ways, but it did not work. I think the default case is from "web.config" to get while .NET Core is appsettings.json.

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    Can you return correct connectionString in this method to see if it works on server with correct connectionString ?

    private static string GetConnectionString()
    {
        return "CorrectConnectionStringHere....";
    }
    

    Then we can try to fix getting correct connection string problem for your second DbContext.

  • User Avatar
    0
    goldstar25 created

    So sure yes, I have tried. But still thank you. This bug fixes please let me know.

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    Did it worked when you return connection string from GetConnectionString method ?

    Thanks.

  • User Avatar
    0
    goldstar25 created

    Yes,it's ok!I wrote the connection string in the code...

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    It is good. Can you send your both DbContext classes to <a href="mailto:[email protected]">[email protected]</a> ? We will take a look at it to fix your main problem.

    Thanks.

  • User Avatar
    0
    goldstar25 created

    Mail has been sent.