Calling an async method from the database seed method

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

Question

I want to know how to call an object in an MVC 5 internet application that I'm developing.async approach from theseed when a database is built, method.

This is my code:

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

At the moment, calling theSetupAdminAndSampleObjectsDatabase I am experiencing 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.

The approach is described as follows:

public async Task SetupAdminAndSampleObjectsDatabase()

Multiple objects are being added using this procedure.

Do I understand correctly that the aforementioned mistake will be fixed if theSetupAdminAndSampleObjectsDatabase a method is called usingawait keyword?

In conclusion, how do I dial aasync approach utilizing a databaseseed method? Can this be done?

I appreciate it.

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

Accepted Answer

You can choose between two options:

1) Use await and make the Seed function async.

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

2) On the async method, use the.WaitAndUnwrapException() method.

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

Hope that was useful.

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