Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF 4.1 Code First - add column

I have my database already set, I want to add a new field to the model, a new column to the table, is there a way I can do this without losing all my data? Normally if you delete the DB it will recreate everything automatically but I don't want to lose the data. I'm using SQL Server 2008 as database.

like image 354
gosukiwi Avatar asked May 24 '12 16:05

gosukiwi


2 Answers

You will need to use EF Migrations to add the new column to your database. You can read more about EF Migrations here and here.

like image 80
david.s Avatar answered Oct 13 '22 06:10

david.s


If you're using code first, I've always just added the column to the database manually in situations like that. Unfortunately, there is no simple way to automate incremental model updates with Code First.

For example, one of EF Code First's own errors even specify manual update as the best option:

The model backing the ‘your context’ context has changed since the database was created. Either manually delete/update the database, or call Database SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

like image 35
Ayo I Avatar answered Oct 13 '22 07:10

Ayo I