Entity-framework – How to use Entity Framework in Code First Drop-Create mode

code-firstentity-framework

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?

Best Answer

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());