gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:54:37 24 4
gpt4 key购买 nike

我正在编写一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com