实体框架6中的多异步?

这是我的暗号:

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

但当我从控制器调用函数时,出现了错误

在上一个异步操作完成之前,在此上下文上启动第二个操作。在调用此上下文上的另一个方法之前,使用“ wait”确保任何异步操作已经完成。不能保证任何实例成员都是线程安全的。

请帮我解决这个问题。

42916 次浏览

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);

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

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:

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

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