Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel Query Execution In Entity Framework Core

Since EF Core can't handle parallel queries at the same time on the same context instance as documentation says, is there any common pattern that we can achieve this in .NET Core 6 using dependency injection?

Given the condition that I have no write and all of them are .AsNoTracking in this scope.

like image 489
Nima Soufiloo Avatar asked Jun 07 '26 21:06

Nima Soufiloo


1 Answers

Quoting MS Documentation:

The recommended approach to create a new DbContext with dependencies is to use a factory.

builder
   .Services
   .AddDbContextFactory<ContactContext>(opt =>
       opt
       .UseSqlite($"Data Source={nameof(ContactContext.ContactsDb)}.db"));

You can get the factory on constructor via DI as usual:

    IDbContextFactory<ContactContext> DbFactory

And create as many contexts as you need, don't forgot to dispose contexts.

using var context = DbFactory.CreateDbContext();
like image 148
dani herrera Avatar answered Jun 10 '26 11:06

dani herrera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!