Calling an async method from a database seed method
I am coding an MVC 5 internet application and would like to know how to call a method async
from a method seed
when creating a database.
Here is my code:
public class ApplicationDbInitializer : CreateDatabaseIfNotExists<ApplicationDbContext>
{
protected override void Seed(ApplicationDbContext context) {
SetupAdminAndSampleObjectsDatabase();
base.Seed(context);
}
}
Currently the SetupAdminAndSampleObjectsDatabase
following error is thrown when calling the method :
System.NotSupportedException: The second operation started on this context before the previous asynchronous operation completed. using "wait" to ensure that all asynchronous operations have completed before calling another method in this context. Any member of the instance is not guaranteed to be thread safe.
Here is the definition of the method:
public async Task SetupAdminAndSampleObjectsDatabase()
I am adding multiple objects to this method.
Am I correct in saying that the above error will be resolved if the method SetupAdminAndSampleObjectsDatabase
is called with a keyword await
?
So, in general, how can I call a method async
from a database method seed
? Is it possible?
Thanks in advance.
source to share
You can do one of two things:
1) Make the Seed method asynchronous and use wait
protected override async void Seed(ApplicationDbContext context) {
await SetupAdminAndSampleObjectsDatabase();
base.Seed(context);
}
2) Use .WaitAndUnwrapException () method for async method
protected override void Seed(ApplicationDbContext context) {
SetupAdminAndSampleObjectsDatabase().WaitAndUnwrapException();
base.Seed(context);
}
Hope it helps!
source to share