Search code examples
c#asynchronousasp.net-mvc-5entity-framework-6initializer

Calling an async method from the database seed method


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.


Solution

  • 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!