Multi-async in Entity Framework 6?

Entity FrameworkAsynchronousEntity Framework-6

Entity Framework Problem Overview


This is my code:

var banner = context.Banners.ToListAsync()
var newsGroup = context.NewsGroups.ToListAsync()
await Task.WhenAll(banner, newsGroup);

But when i called the function from controller. It showed error

>A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe.

Please help me solve this issue.

Entity Framework Solutions


Solution 1 - Entity Framework

The exception explains clearly that there is only one asynchronous operation per context allowed at a time.

So, you either have to await them one at a time as the error message suggests:

var banner = await context.Banners.ToListAsync();
var newsGroup = await context.NewsGroups.ToListAsync();

Or you can use multiple contexts:

var banner = context1.Banners.ToListAsync();
var newsGroup = context2.NewsGroups.ToListAsync();
await Task.WhenAll(banner, newsGroup);

Solution 2 - Entity Framework

If you are using IoC container for your Data Provider injection, consider to use "transient" or "PerWebRequest" type for your lifecycle.

For example: https://github.com/castleproject/Windsor/blob/master/docs/lifestyles.md

Solution 3 - Entity Framework

If you use Unity for dependency injection with for example repository pattern you will get the following error using two or more contexts with create/update/delete:

> The relationship between the two objects cannot be defined because > they are attached to different ObjectContext objects.

This can be solved using PerRequestLifetimeManager. More info here:

https://stackoverflow.com/questions/45146126/c-sharp-ef6-make-multiple-async-calls-to-one-context-using-unity-asp-net-web-a/45162704#45162704

container.RegisterType<DbContext>(new PerRequestLifetimeManager());
container.RegisterType<ISupplierRepository, SupplierRepository>();
container.RegisterType<IContactRepository, ContactRepository>();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAn HvView Question on Stackoverflow
Solution 1 - Entity FrameworkStephen ClearyView Answer on Stackoverflow
Solution 2 - Entity FrameworkTeoman shipahiView Answer on Stackoverflow
Solution 3 - Entity FrameworkOgglasView Answer on Stackoverflow