bbrinck
bbrinck

Reputation: 1103

.NET MediatR and EF Core DbContext The connection does not support MultipleActiveResultSets

I am using MediatR to handle my requests and I need to inject the DbContext from EF Core (ApplicationDbContext). I used an interface to do so.

The first request works fine, but immediatly after, the second request fails with this message:

The connection does not support MultipleActiveResultSets.

I do not want to enable MultipleActiveResultSets, I just want to figure out why this is happening.

Here is my Startup.cs:

services.AddPersistence(Configuration);
            
services.AddInfrastructure(Configuration);
            
services.AddApplication();

In the AddPersistence I register my ApplicationDbContext and add the IApplicationDbContext interface as Scoped:

services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(dbConnectionString)
            );
            
services.AddScoped<IApplicationDbContext>(provider => provider.GetService<ApplicationDbContext>());

Here my IApplicationDbContext Interface:

public interface IApplicationDbContext
    {
        DbSet<MyEntity> MyEntities { get; set; }

        Task<int> SaveChangesAsync(CancellationToken cancellationToken);
    }

My ApplicationDbContext:

public sealed class ApplicationDbContext : DbContext, IApplicationDbContext
    {
        public DbSet<MyEntity> MyEntities{ get; set; }

        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {
            Database.EnsureCreated();
            
            Database.Migrate();
        }
        
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
        }
    }

Now in the MediatR Handler I do this:

private readonly IApplicationDbContext _applicationDbContext;

public FilterAircraftDelayCodesRequestHandler(IApplicationDbContext applicationDbContext)
{
    _applicationDbContext = applicationDbContext;
}

I just want to return a list of my objects from the ApplicationDbContext DbSet in the MediatR Handler:

var data = await _applicationDbContext.MyEntites.ToListAsync(cancellationToken: cancellationToken);

And here the exception that I get:

System.InvalidOperationException: The connection does not support MultipleActiveResultSets.
   at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__164_0(Task`1 result)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.Tasks.Task.<>c.<.cctor>b__274_0(Object obj)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(DbContext _, Boolean result, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 sou...

Upvotes: 0

Views: 1827

Answers (1)

bbrinck
bbrinck

Reputation: 1103

In this case the issue was in the constructor of the ApplicationDbContext.

I used Database.MigrateAsync(), which produced this error.

I resolved this exception by using the Database.Migrate() method in a non-async way.

Upvotes: 2

Related Questions