EF Core: drop and recreate database when server restarts

asp.net-core asp.net-core-mvc c# entity-framework-core

Question

We have an ASP.NET Core MVC application with Entity Framework Core in it. We have added a custom Testing environment to the existing Development, Staging and Production environments. Now, we would like the application to drop and recreate (or at least truncate) the database every time the application starts in this new Testing environment.

Is there an automated way how to achieve this behavior? Or do I have to manually call RemoveAll on each DbSet in the database context?

1
2
10/19/2017 8:30:53 AM

Accepted Answer

Call dbContext.Database.EnsureDeleted();

Ensures that the database for the context does not exist. If it does not exist, no action is taken. If it does exist then the database is deleted.

Warning: The entire database is deleted an no effort is made to remove just the database objects that are used by the model for this context.

Then call dbContext.Database.Migrate() to create new (empty) DB and migrate to latest version.

9
10/19/2017 9:01:16 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