Open Closed

Cannot use multiple context instances within a single query execution #8539


User avatar
0
adnan.aldaim@decisiontree.tech created
  • ABP Framework version: v8.3.2
  • UI Type: Angular
  • Database System: EF Core (PostgreSQL)
  • Auth Server Separated (for Angular): yes
  • Exception message and full stack trace: [ERR] Cannot use multiple context instances within a single query execution. Ensure the query uses a single context instance. System.InvalidOperationException: Cannot use multiple context instances within a single query execution. Ensure the query uses a single context instance. at Microsoft.EntityFrameworkCore.Query.Internal.ParameterExtractingExpressionVisitor.VisitExtension(Expression extensionExpression) at Microsoft.EntityFrameworkCore.Query.Internal.ParameterExtractingExpressionVisitor.Visit(Expression expression) at System.Dynamic.Utils.ExpressionVisitorUtils.VisitArguments(ExpressionVisitor visitor, IArgumentProvider nodes) at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node) at Microsoft.EntityFrameworkCore.Query.Internal.ParameterExtractingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) at Microsoft.EntityFrameworkCore.Query.Internal.ParameterExtractingExpressionVisitor.Visit(Expression expression) at System.Dynamic.Utils.ExpressionVisitorUtils.VisitArguments(ExpressionVisitor visitor, IArgumentProvider nodes) at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node) at Microsoft.EntityFrameworkCore.Query.Internal.ParameterExtractingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) at Microsoft.EntityFrameworkCore.Query.Internal.ParameterExtractingExpressionVisitor.Visit(Expression expression) at System.Dynamic.Utils.ExpressionVisitorUtils.VisitArguments(ExpressionVisitor visitor, IArgumentProvider nodes) at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node) at Microsoft.EntityFrameworkCore.Query.Internal.ParameterExtractingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) at Microsoft.EntityFrameworkCore.Query.Internal.ParameterExtractingExpressionVisitor.Visit(Expression expression) at System.Dynamic.Utils.ExpressionVisitorUtils.VisitArguments(ExpressionVisitor visitor, IArgumentProvider nodes) at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node) at Microsoft.EntityFrameworkCore.Query.Internal.ParameterExtractingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) at Microsoft.EntityFrameworkCore.Query.Internal.ParameterExtractingExpressionVisitor.Visit(Expression expression) at System.Dynamic.Utils.ExpressionVisitorUtils.VisitArguments(ExpressionVisitor visitor, IArgumentProvider nodes) at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node) at Microsoft.EntityFrameworkCore.Query.Internal.ParameterExtractingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) at Microsoft.EntityFrameworkCore.Query.Internal.ParameterExtractingExpressionVisitor.Visit(Expression expression) at Microsoft.EntityFrameworkCore.Query.Internal.ParameterExtractingExpressionVisitor.ExtractParameters(Expression expression, Boolean clearEvaluatedValues) at Microsoft.EntityFrameworkCore.Query.Internal.ParameterExtractingExpressionVisitor.ExtractParameters(Expression expression) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExtractParameters(Expression query, IParameterValues parameterValues, IDiagnosticsLogger1 logger, Boolean parameterize, Boolean generateContextAccessors) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query) at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression) at Volo.Abp.EntityFrameworkCore.AbpEntityQueryProvider.Execute[TResult](Expression expression) at ClientelePortal.ClientManagement.Clients.ClientAppService.GetListAsync(GetClientInput input) in D:\DecisionTreeTech\ClienteleProject\upgrade_v8\ClientelePortal\aspnet-core\modules\ClientelePortal.ClientManagement\src\ClientelePortal.ClientManagement.Application\Clients\ClientAppService.cs:line 322 at Castle.DynamicProxy.AsyncInterceptorBase.ProceedAsynchronous[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo) at Volo.Abp.Castle.DynamicProxy.CastleAbpMethodInvocationAdapterWithReturnValue1.ProceedAsync() at Volo.Abp.Authorization.AuthorizationInterceptor.InterceptAsync(IAbpMethodInvocation invocation) at Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter1.InterceptAsync[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo, Func3 proceed) at Castle.DynamicProxy.AsyncInterceptorBase.ProceedAsynchronous[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo) at Volo.Abp.Castle.DynamicProxy.CastleAbpMethodInvocationAdapterWithReturnValue1.ProceedAsync() at Volo.Abp.GlobalFeatures.GlobalFeatureInterceptor.InterceptAsync(IAbpMethodInvocation invocation) at Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter1.InterceptAsync[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo, Func3 proceed) at Castle.DynamicProxy.AsyncInterceptorBase.ProceedAsynchronous[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo) at Volo.Abp.Castle.DynamicProxy.CastleAbpMethodInvocationAdapterWithReturnValue1.ProceedAsync() at Volo.Abp.Auditing.AuditingInterceptor.ProceedByLoggingAsync(IAbpMethodInvocation invocation, AbpAuditingOptions options, IAuditingHelper auditingHelper, IAuditLogScope auditLogScope) at Volo.Abp.Auditing.AuditingInterceptor.InterceptAsync(IAbpMethodInvocation invocation) at Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter1.InterceptAsync[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo, Func3 proceed) at Castle.DynamicProxy.AsyncInterceptorBase.ProceedAsynchronous[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo) at Volo.Abp.Castle.DynamicProxy.CastleAbpMethodInvocationAdapterWithReturnValue1.ProceedAsync() at Volo.Abp.Features.FeatureInterceptor.InterceptAsync(IAbpMethodInvocation invocation) at Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter1.InterceptAsync[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo, Func3 proceed) at Castle.DynamicProxy.AsyncInterceptorBase.ProceedAsynchronous[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo) at Volo.Abp.Castle.DynamicProxy.CastleAbpMethodInvocationAdapterWithReturnValue1.ProceedAsync() at Volo.Abp.Validation.ValidationInterceptor.InterceptAsync(IAbpMethodInvocation invocation) at Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter1.InterceptAsync[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo, Func3 proceed) at Castle.DynamicProxy.AsyncInterceptorBase.ProceedAsynchronous[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo) at Volo.Abp.Castle.DynamicProxy.CastleAbpMethodInvocationAdapterWithReturnValue1.ProceedAsync() at Volo.Abp.Uow.UnitOfWorkInterceptor.InterceptAsync(IAbpMethodInvocation invocation) at Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter1.InterceptAsync[TResult](IInvocation invocation, IInvocationProceedInfo proceedInfo, Func3 proceed) at ClientelePortal.ClientManagement.Clients.ClientController.GetListAsync(GetClientInput input) in D:\DecisionTreeTech\ClienteleProject\upgrade_v8\ClientelePortal\aspnet-core\modules\ClientelePortal.ClientManagement\src\ClientelePortal.ClientManagement.HttpApi\Clients\ClientController.cs:line 51 at lambda_method3736(Closure, Object) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask1 actionResultValueTask) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
    • Steps to reproduce the issue: I have multiple entities. The "Clients" entity present in the abp module(ClientManagement) and "Users" present in the root EntityFrameworkCore project of the application. When ever I am going to join these two entities as Queryable it throws exception above.
    public class ClientManagementDbContext :
    AbpDbContext<ClientManagementDbContext>
{
    public DbSet<Company> Companies { get; set; }
    public DbSet<Client> Clients { get; set; }
    public DbSet<Location> Locations { get; set; }

    public ClientManagementDbContext(DbContextOptions<ClientManagementDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<Company>(b =>
        {
            b.ToTable("AppCompanies");
        });

        builder.Entity<Client>(b =>
        {
            b.ToTable("AppClients");
        });

        builder.Entity<Location>(b =>
        {
            b.ToTable("AppLocations");
        });
    }
}

[ReplaceDbContext(typeof(IIdentityProDbContext))]
[ReplaceDbContext(typeof(ISaasDbContext))]
[ConnectionStringName("Default")]
public class ClientelePortalDbContext :
    AbpDbContext<ClientelePortalDbContext>,
    ISaasDbContext,
    IIdentityProDbContext
{
    public DbSet<NotificationSettings> NotificationSettings { get; set; }
    public DbSet<FAQQuestion> FAQQuestions { get; set; }
    public DbSet<FAQSection> FAQSections { get; set; }
    public DbSet<IdentityUser> Users { get; set; }
    public DbSet<IdentityRole> Roles { get; set; }
    public DbSet<IdentityClaimType> ClaimTypes { get; set; }
    public DbSet<OrganizationUnit> OrganizationUnits { get; set; }
    public DbSet<IdentitySecurityLog> SecurityLogs { get; set; }
    public DbSet<IdentityLinkUser> LinkUsers { get; set; }
    public DbSet<IdentityUserDelegation> UserDelegations { get; set; }
    public DbSet<IdentitySession> Sessions { get; set; }
    public DbSet<Tenant> Tenants { get; set; }
    public DbSet<Edition> Editions { get; set; }
    public DbSet<TenantConnectionString> TenantConnectionStrings { get; set; }
    public ClientelePortalDbContext(DbContextOptions<ClientelePortalDbContext> options)
        : base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        /* Include modules to your migration db context */
        builder.ConfigureClientelePortal();
        builder.ConfigurePermissionManagement();
        builder.ConfigureSettingManagement();
        builder.ConfigureBackgroundJobs();
        builder.ConfigureAuditLogging();
        builder.ConfigureFeatureManagement();
        builder.ConfigureIdentityPro();
        builder.ConfigureOpenIddict();
        builder.ConfigureLanguageManagement();
        builder.ConfigureFileManagement();
        builder.ConfigureSaas();
        builder.ConfigureTextTemplateManagement();
        builder.ConfigureCmsKit();
        builder.ConfigureCmsKitPro();
        builder.ConfigureBlobStoring();
        builder.ConfigurePayment();
    }
}
  public async Task<PagedResultDto<ClientListDto>> GetListAsync(GetClientInput input)
  {
      List<ClientListDto> clients = new();
      input.CompanyId = input.CompanyId == null || input.CompanyId == Guid.Empty ? null : input.CompanyId;
      if (input.Sorting.IsNullOrWhiteSpace())
      {
          input.Sorting = nameof(Client.CreationTime) + " desc";
      }
      var clientQueryable = await _clientRepository.GetQueryableAsync();
      var userQueryable = await _userRepository.GetQueryableAsync();
      var locationQueryable = await _locationRepository.GetQueryableAsync();

      if (clientQueryable.Count() == 0)
      {
          return new PagedResultDto<ClientListDto>(
              0,
              null
      );
      }
      var query = (from client in clientQueryable
                   join user in userQueryable on client.UserId equals user.Id
                   join location in locationQueryable on client.CountryId equals location.Id
                   where !client.IsDeleted && client.TenantId == CurrentTenant.Id
                         && !user.IsDeleted && user.TenantId == CurrentTenant.Id
                   select new ClientListDto
                   {
                       Id = client.Id,
                       CreationTime = client.CreationTime,
                       TenantId = client.TenantId,
                       Name = user.Name,
                       Surname = user.Surname,
                       Email = user.Email,
                       CellPhone = user.PhoneNumber,
                       Phone = client.Phone,
                       Title = client.Title,
                       Note = client.Note,
                       UserId = client.UserId,
                       Location = location.Name,
                       CountryId = client.CountryId,
                       CompanyIds = client.CompanyIds,
                       IsInvited = client.IsInvited
                   }).AsQueryable();

          query = query
          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), m =>
              m.Name.ToLower().Contains(input.FilterText.ToLower()) ||
              m.Surname.ToLower().Contains(input.FilterText.ToLower()) ||
              m.CellPhone.Contains(input.FilterText) ||
              m.Email.ToLower().Contains(input.FilterText.ToLower()) ||
              m.Phone.Contains(input.FilterText) ||
              m.Title.ToLower().Contains(input.FilterText.ToLower()))
          .WhereIf(!input.Name.IsNullOrWhiteSpace(), m => m.Name.ToLower().Contains(input.Name.ToLower()))
          .WhereIf(!input.Surname.IsNullOrWhiteSpace(), m => m.Surname.ToLower().Contains(input.Surname.ToLower()))
          .WhereIf(!input.CellPhone.IsNullOrWhiteSpace(), m => m.CellPhone.Contains(input.CellPhone))
          .WhereIf(!input.Email.IsNullOrWhiteSpace(), m => m.Email.ToLower().Contains(input.Email.ToLower()))
          .WhereIf(!input.Phone.IsNullOrWhiteSpace(), m => m.Phone.Contains(input.Phone))
          .WhereIf(!input.Title.IsNullOrWhiteSpace(), m => m.Title.ToLower().Contains(input.Title.ToLower()))
          .WhereIf(input.CompanyId.HasValue, m => m.CompanyIds.Contains(input.CompanyId.Value))
          .WhereIf(input.LocationId.HasValue, m => m.CountryId == input.LocationId.Value);

      var totalCount = query.Count();

      clients = await AsyncExecuter.ToListAsync(query.OrderBy(input.Sorting)
                                                            .Skip(input.SkipCount)
                                                            .Take(input.MaxResultCount)
                                                    );

      clients.ForEach(async c => c.IsAlreadyLogin = await _identitySecurityLogs.AnyAsync(x => x.UserId == c.UserId && x.TenantId == c.TenantId && x.Action == "LoginSucceeded"));

      return new PagedResultDto<ClientListDto>(
              totalCount,
              clients
      );
  }

2 Answer(s)
  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi,

    Because they are in the different db contexts, so you can't use join queries

  • User Avatar
    0
    Sergei.Gorlovetsky created

    Hi, could you elaborate please.

Made with ❤️ on ABP v9.1.0-preview. Updated on December 26, 2024, 06:07