question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Error using two DbContexts from same AppService Method (dotnetcore)

See original GitHub issue

Hello there. Im having the same problem from #1706 but none of the solutions from that issue solved my problem. I have posted same question there, but I’ve decided to open a new issue since that one is already closed.

  • Your Abp package version: 2.1.3
  • Your base framework: .Net Framework or .Net Core: .Net Core
  • Exception message and stack trace if available:
System.InvalidOperationException: The specified transaction is not associated with the current connection. Only transactions associated with the current connection may be used.
   at Microsoft.EntityFrameworkCore.Storage.RelationalTransaction..ctor(IRelationalConnection connection, DbTransaction transaction, ILogger logger, Boolean transactionOwned)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.UseTransaction(DbTransaction transaction)
   at Abp.EntityFrameworkCore.Uow.DbContextEfCoreTransactionStrategy.CreateDbContext[TDbContext](String connectionString, IDbContextResolver dbContextResolver)
   at Abp.EntityFrameworkCore.Uow.EfCoreUnitOfWork.GetOrCreateDbContext[TDbContext](Nullable`1 multiTenancySide)
   at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase`3.get_Table()
   at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase`3.GetAllIncluding(Expression`1[] propertySelectors)
   at Castle.Proxies.Invocations.IRepository`2_GetAll_30.InvokeMethodOnTarget()
   at Castle.DynamicProxy.AbstractInvocation.Proceed()
   at Abp.Domain.Uow.UnitOfWorkInterceptor.PerformSyncUow(IInvocation invocation, UnitOfWorkOptions options)
   at Castle.DynamicProxy.AbstractInvocation.Proceed()
   at Castle.Proxies.IBusinessIntelligenceRepository`2Proxy.GetAll()
   at Erp.BusinessIntelligence.Dashboards.DashboardAppService.<GetDashboards>d__6.MoveNext() in C:\Users\Bruno\Work\NgIT\Korp\Erp\aspnet-core\src\Modules\BusinessIntelligence\Erp.BusinessIntelligence.Application\Dashboards\DashboardAppService.cs:line 55
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ObjectMethodExecutor.<CastToObject>d__38`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__27.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextActionFilterAsync>d__25.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextExceptionFilterAsync>d__24.MoveNext()

@hikalkan would you please shed some light, im struggling with this.

None of the solutions above have worked for me.

Here is my structure:

Default AspNetZero project created so I have Erp.EntityFrameworkCore project Project set for custom module: Core/App/EFCore/WebCore.

For the record I have created the same structure for EFCore module. With a single DbContext everything works fine. When I User one repository from another dbcontext (main abp core module like User) it throws the exception:

The specified transaction is not associated with the current connection. Only transactions associated with the current connection may be used.

ErpEntityFrameworkCoreModule – from Abp

/// <summary>
    /// Entity framework Core module of the application.
    /// </summary>
    [DependsOn(
        typeof(AbpZeroCoreEntityFrameworkCoreModule), 
        typeof(ErpCoreModule), 
        typeof(AbpZeroCoreIdentityServerEntityFrameworkCoreModule)
        )]
    public class ErpEntityFrameworkCoreModule : AbpModule
    {
        /* Used it tests to skip dbcontext registration, in order to use in-memory database of EF Core */
        public bool SkipDbContextRegistration { get; set; }

        public bool SkipDbSeed { get; set; }

        public override void PreInitialize()
        {
            Configuration.ReplaceService<IEfCoreTransactionStrategy, DbContextEfCoreTransactionStrategy>(DependencyLifeStyle.Transient);

            if (!SkipDbContextRegistration)
            {
                Configuration.Modules.AbpEfCore().AddDbContext<ErpDbContext>(configuration =>
                {
                    ErpDbContextConfigurer.Configure(configuration.DbContextOptions, configuration.ConnectionString);
                });
            }
        }

        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(typeof(ErpEntityFrameworkCoreModule).GetAssembly());
        }

        public override void PostInitialize()
        {
            if (!SkipDbSeed)
            {
                SeedHelper.SeedHostDb(IocManager);
            }
        }
    }

CustomServiceEntityFrameworkCoreModule

[DependsOn(
        typeof(CustomServiceCoreModule),
        typeof(ErpEntityFrameworkCoreModule)
    )]
    public class CustomServiceEntityFrameworkCoreModule : AbpModule
    {
        /* Used it tests to skip dbcontext registration, in order to use in-memory database of EF Core */
        public bool SkipDbContextRegistration { get; set; }

        public bool SkipDbSeed { get; set; }

        public override void PreInitialize()
        {
            Configuration.ReplaceService<IEfCoreTransactionStrategy, DbContextEfCoreTransactionStrategy>(DependencyLifeStyle.Transient);

            if (!SkipDbContextRegistration)
            {
                Configuration.Modules.AbpEfCore().AddDbContext<CustomServiceDbContext>(configuration =>
                {
                    CustomServiceDbContextConfigurer.Configure(configuration.DbContextOptions, configuration.ConnectionString);
                });
            }
        }

        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(typeof(CustomServiceEntityFrameworkCoreModule).GetAssembly());
        }

        public override void PostInitialize()
        {
            if (!SkipDbSeed)
            {
                CustomServiceSeedHelper.SeedDataConnectionsDb(IocManager);
            }
        }
    }

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:15 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
iyhammadcommented, Aug 27, 2017

Hello, I’m facing the exact same issue after upgrading my solution to EFCore. I’ve Core System and multiple modules and every module has its own Db Context. the Solution is also multi-tenancy. I’ve one HostDbContext for Host and has fixed connection string coming from the configuration. I’ve TenantDbContext per module (Total 4 modules for now). In EF6 the same structure was working fine. now in EFCore I got the mentioned exception. Could your please help us in this issue. Thanks,

0reactions
hikalkancommented, Sep 5, 2017

Please re-open if you have the problem again.

Read more comments on GitHub >

github_iconTop Results From Across the Web

dotnet Core - Entity Framework - Multiple DbContexts ...
Essentially I needed to use a generic options type. So, I changed my constructor in each DbContext to reflect what it actually is....
Read more >
Using Multiple EF Core DbContexts In a Single Application
You have to create a new transaction and share it between the DbContexts by calling the UseTransaction method.
Read more >
Cannot use multiple context instances within a single query ...
I am getting error for multiple dbcontext like Cannot use multiple context instances within a single query execution. Ensure the query uses ...
Read more >
Some services are not able to be constructed dbcontext
Hi All, I am migrating one asp.net core 3.1 from asp.net project. Here i have one dbcontext which connection string i need to...
Read more >
Unable to resolve service for type in .NET 5 with entity ...
Hi I am trying to do a website using .NET 5 with some entity framework 3.1.21. I get this error on my Comments/index...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found