Calling an async method from the database seed method

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

Question

I am coding a MVC 5 internet application and would like to know how to call an async method from the seed method when a database is created.

Here is my code:

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

Currently, when calling the SetupAdminAndSampleObjectsDatabase method, I am getting the following error:

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.

Here is the method definition:

public async Task SetupAdminAndSampleObjectsDatabase()

I am adding multiple objects in this method.

Am I correct in saying that the above error will be resolved if the SetupAdminAndSampleObjectsDatabase method is called with the await keyword?

So, in summary, how can I call an async method from the database seed method? Is this possible?

Thanks in advance.

1
3
5/18/2015 1:49:37 AM

Accepted Answer

You can do one of two things:

1) Make the Seed method async, and use await

protected override async void Seed(ApplicationDbContext context) {            
        await SetupAdminAndSampleObjectsDatabase();
        base.Seed(context);
    }

2) Use .WaitAndUnwrapException() on the async method

protected override void Seed(ApplicationDbContext context) {            
        SetupAdminAndSampleObjectsDatabase().WaitAndUnwrapException();
        base.Seed(context);
    }

Hope that helps!

2
5/18/2015 2:43:31 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow