0

I am studing model first approach in Entity Framework. I found all data gets wiped out whenever a re-generation of the database from the model occurs. Is model-first really a useful approach or is there a way to fix this

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Joseph Bi
  • 1,166
  • 2
  • 9
  • 11

4 Answers4

2

Model first doesn't delete your data automatically. It creates SQL script for database creation and if you execute it, it will probably drop all your tables but you can change the script manually or you can use some advanced tool for database upgrade:

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
1

Entity Framework drops your database and re-creates it from scratch. That's just the way it works. Microsoft is working on a migration strategy that will allow you to migrate changes, but that is not going to be ready until the next major version.

There are some third party tools that attempt to solve this problem, but I wouldn't be too dependant upon them.

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
0

Whenever you update the model and run the auto-generated SQL script, you can manually seed the database to get your data back. Seeding doesn't work the same in Model-First as it does in Code-First, so the oft-talked-about and helpful DropAndCreateDatabaseIfModelChanges approach doesn't work so well. The easiest work around is to seed manually by initialising yourself.

var db = new MyDbContext();
db.Database.Initialize(true);
0

One of the way to deal with this problem is to seed your data i.e. populate the database with some test data after EF creates it. See http://binuity.com/blog/2011/03/28/ef4-seeding-data-on-each-dropcreatedatabaseifmodelchanges/

Yet another way is to have tools that would try to update database instead of re-creating it.

VinayC
  • 47,395
  • 5
  • 59
  • 72
  • Only applicable to Code First – cdm9002 Jun 26 '12 at 19:08
  • @cdm9002, yes the sample code for seeding is applicable for Code First only but its possible to seed your data in Model First as well as. All you have to do is to write the code that inserts seed data into the database (e.g. something like http://msdn.microsoft.com/en-us/library/ff407091.aspx). However, OP here is probably more interested in retaining his data and that's possible only using some tools! – VinayC Jun 27 '12 at 11:54