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.
Yes.It's works on my computer,but not works on server.
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.<>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.<InvokeActionMethodAsync>d__27.MoveNext()
--- 引发异常的上一位置中堆栈跟踪的末尾 ---
在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
在 Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextActionFilterAsync>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.<InvokeNextExceptionFilterAsync>d__24.MoveNext()
It's OK!Thanks! And need add these code to set tenantId filter:
CurrentUnitOfWork.SetFilterParameter(AbpDataFilters.MayHaveTenant, AbpDataFilters.Parameters.TenantId, tenantId);
Source code:[attachment=0:3g29fpyl]SyncWeChatUsersJob.zip[/attachment:3g29fpyl] SyncWeChatUsersJob.zip
Hi,
When I use IRepository in BackgroundJob on**.NET Core**,It’s throw this exception:
发生了 System.InvalidOperationException
HResult=0x80131509
Message=The operation cannot be completed because the DbContext has been disposed.
Source=EntityFramework
StackTrace:
在 System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
在 System.Data.Entity.Internal.Linq.InternalQuery1.GetEnumerator() 在 System.Data.Entity.Internal.Linq.InternalSet
1.GetEnumerator()
在 System.Data.Entity.Infrastructure.DbQuery1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() 在 System.Collections.Generic.List
1..ctor(IEnumerable1 collection) 在 System.Linq.Enumerable.ToList[TSource](IEnumerable
1 source)
在 Magicodes.WeChat.Application.BackgroundJob.SyncWeChatUsersJob.Execute(Int32 args) 在 E:\workspace\Magicodes.Admin.Core\plus\Magicodes.WeChat\Magicodes.WeChat.Application\BackgroundJob\SyncWeChatUsersJob.cs 中: 第 26 行
hope to get your support!
Now,no exception,but L function not work.I use this code in view:
<p>
@L("Test")
<br />
@(LocalizationHelper.GetString(TestDemoConsts.LocalizationSourceName, "Test"))
</p>
It's not work.it print "[Test] ". And the xml content is:
<?xml version="1.0" encoding="utf-8"?>
<localizationDictionary culture="en">
<texts>
<text name="Test" value="Test Test Test" />
</texts>
</localizationDictionary>
I has config "TestLocalizationConfigurer":
namespace TestDemo.Localization
{
public class TestLocalizationConfigurer
{
public static void Configure(ILocalizationConfiguration localizationConfiguration)
{
localizationConfiguration.Sources.Add(
new DictionaryBasedLocalizationSource(
TestDemoConsts.LocalizationSourceName,
new XmlEmbeddedFileLocalizationDictionaryProvider(
Assembly.GetExecutingAssembly(),
"TestDemo.Localization"
)
)
);
}
}
}
And write in AbpModule:
public override void Initialize()
{
//设置语言资源
TestLocalizationConfigurer.Configure(Configuration.Localization);
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
}
I just tested,I found "_ViewStart.cshtml" also not work.
I thought "Views/**/." may be not contains "_ViewImports.cshtml" and "_ViewStart.cshtml",so I have a try,but it also not work. If I add these code in view :
@using Magicodes.Theme.Metronic
It's OK. So I mean the "_ViewImports.cshtml" is not work. And the other problem is "Can't use AreaAttribute in plus Controllers",it's will not found view.