[英]Calling an async method from the database seed method
我正在編寫一個MVC 5 Internet應用程序,並想知道在創建數據庫時如何從seed
方法調用async
方法。
這是我的代碼:
public class ApplicationDbInitializer : CreateDatabaseIfNotExists<ApplicationDbContext>
{
protected override void Seed(ApplicationDbContext context) {
SetupAdminAndSampleObjectsDatabase();
base.Seed(context);
}
}
目前,在調用SetupAdminAndSampleObjectsDatabase
方法時,我收到以下錯誤:
System.NotSupportedException:在上一個異步操作完成之前,在此上下文中啟動了第二個操作。 使用'await'確保在此上下文上調用另一個方法之前已完成任何異步操作。 任何實例成員都不保證是線程安全的。
這是方法定義:
public async Task SetupAdminAndSampleObjectsDatabase()
我在這個方法中添加了多個對象。
我是否正確說如果使用await
關鍵字調用SetupAdminAndSampleObjectsDatabase
方法,將解決上述錯誤?
那么,總之,如何從數據庫seed
方法中調用async
方法? 這可能嗎?
提前致謝。
你可以做以下兩件事之一:
1)使Seed方法異步,並使用await
protected override async void Seed(ApplicationDbContext context) {
await SetupAdminAndSampleObjectsDatabase();
base.Seed(context);
}
2)在異步方法上使用.WaitAndUnwrapException()
protected override void Seed(ApplicationDbContext context) {
SetupAdminAndSampleObjectsDatabase().WaitAndUnwrapException();
base.Seed(context);
}
希望有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.