c# - 从数据库种子方法调用异步方法

标签 c# asynchronous asp.net-mvc-5 entity-framework-6 initializer

我正在编写一个 MVC 5 互联网应用程序,想知道如何在创建数据库时从 seed 方法调用 async 方法。

这是我的代码:

public class ApplicationDbInitializer : CreateDatabaseIfNotExists<ApplicationDbContext> 
{
    protected override void Seed(ApplicationDbContext context) {            
        SetupAdminAndSampleObjectsDatabase();
        base.Seed(context);
    }
}

目前,当调用 SetupAdminAndSampleObjectsDatabase 方法时,出现以下错误:

System.NotSupportedException: 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.

方法定义如下:

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

希望对您有所帮助!

关于c# - 从数据库种子方法调用异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30294019/

相关文章:

c# - 净核心 : Are MVC Controllers default Singleton?

c# - 当使用 Directory.Move 时该文件已存在时无法创建该文件

asp.net-mvc - ASP.NET MVC 5(Visual Studio 2013 预览版)更改 [授权] 的登录 URL

c# - 使用 Windows 身份验证时 MVC5 重定向到 Login.aspx

javascript - 如何在 Rails 中异步/使用 AJAX 呈现部分内容?

c# - GlobalConfiguration.Configure() 在 Web API 2 和 .NET 4.5.1 迁移后不存在

c# - 如何在调整大小的表单上安装控件

c# - 为什么启用 SSL 后仍可通过端口 389 访问事件目录?

java - Netty 处理程序的调用顺序是什么?

node.js - 从回调中设置全局变量