Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 939
Ryan Langton Avatar asked Mar 01 '13 16:03

Ryan Langton


People also ask

How do I use Entity Framework code First?

Step 1 − First, create the console application from File → New → Project… Step 2 − Select Windows from the left pane and Console Application from the template pane. Step 3 − Enter EFCodeFirstDemo as the name and select OK. Step 4 − Right-click on your project in the solution explorer and select Manage NuGet Packages…


Video Answer


1 Answers

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()); 
like image 198
Sergey Berezovskiy Avatar answered Oct 05 '22 19:10

Sergey Berezovskiy