Ryan Langton
Ryan Langton

Reputation: 6160

How do I use Entity Framework in Code First Drop-Create mode?

I'm using Entity Framework v4. I have followed the instructions in the Nerd Dinner tutorial. I'm currently in development mode (not released to any higher environments) and would like for tables to be recreated on each new deployment, since the models are still highly volatile and I don't care to retain data. However, this does not occur. Tables are not created/modified, or anything happening to the DB. If I move to a migrations model by using the Package Manager commands: enable-migrations, add-migration (initial), this works and uses my migrations. However, since I don't yet want to have granular migrations and only want my initial create script, I am forced to delete the migrations folder, redo the commands (enable-migrations, add-migration) and delete the database manually, every time I change anything.

How do I get the drop/create behavior of code first to occur?

Upvotes: 35

Views: 52388

Answers (2)

Sam Yim
Sam Yim

Reputation: 1

If the database already exists and you want to make changes to your model, you use DropCreateDatabaseIfModelChanges<YourContextName>

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

Use DropCreateDatabaseAlways initializer for your database. It will always recreate database during first usage of context in app domain:

Database.SetInitializer(new DropCreateDatabaseAlways<YourContextName>());

Actually if you want to seed your database, then create your own initializer, which will be inherited from DropCreateDatabaseAlways:

public class MyInitializer : DropCreateDatabaseAlways<YourContextName>
{
     protected override void Seed(MagnateContext context)
     {
         // seed database here
     }
}

And set it before first usage of context

Database.SetInitializer(new MyInitializer());

Upvotes: 55

Related Questions