lss
lss

Reputation: 1325

EF Core: drop and recreate database when server restarts

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?

Upvotes: 2

Views: 8716

Answers (1)

Dmitry
Dmitry

Reputation: 16795

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.

Upvotes: 12

Related Questions