Multi-async in Entity Framework 6?

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 the controller. He showed a mistake

The second operation began in this context before the completion of the previous asynchronous operation. Use "wait" to ensure that any asynchronous operations were performed before calling another method in this context. Any instance members do not guarantee thread safety.

Please help me solve this problem.

+67
asynchronous entity-framework entity-framework-6
Dec 17 '13 at 7:57
source share
3 answers

The exception explains that there is only one asynchronous operation for each allowed context.

Thus, you should either await them one at a time, as the error message indicates:

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

Or you can use several contexts:

 var banner = context1.Banners.ToListAsync(); var newsGroup = context2.NewsGroups.ToListAsync(); await Task.WhenAll(banner, newsGroup); 
+87
Dec 17 '13 at 13:10
source share

If you use an IoC container to inject a data provider, consider using a transition type or a PerWebRequest for your life cycle.

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

+4
Nov 11 '16 at 20:38
source share

If you use Unity to inject dependencies with an example repository template, you will receive the following error using two or more contexts with create / update / delete:

The relationship between two objects cannot be determined because they are bound to different ObjectContext objects.

This can be solved using PerRequestLifetimeManager . More details here:

C # EF6 make multiple asynchronous calls in one context using Unity - Asp.Net Web Api

 container.RegisterType<DbContext>(new PerRequestLifetimeManager()); container.RegisterType<ISupplierRepository, SupplierRepository>(); container.RegisterType<IContactRepository, ContactRepository>(); 
+1
Jul 18 '17 at 9:30
source share



All Articles