Reputation: 2643
I'm trying to get a grip on Code First and so far every time I make a change to a model I need to drop and recreate the database. What about the data that's currently in the database? I just find it annoying that I have to do this every time and doesn't make for a a good web approach unless you are 100% sure you'll never have to make a change such as adding a new column in a table. Is there another way to prevent this from happening?
Upvotes: 4
Views: 1861
Reputation: 3999
If you are trying to maintain test data during development consider using the Seed method of IDatabaseInitializer (ie. your database initializer). The Seed method is called during itialization (after any model changes are applied) and will populate any test data you specify.
The best way to specify which initializer you want EF to use is in the global.asax.cs file.
Here's an example:
[Global.asax.cs]
Database.SetInitializer<MyApplicationDbContext>(new MyApplicationDbContextInitializer());
[MyApplicationDbContextInitializer.cs]
public class MyApplicationDbContextInitializer : DropCreateDatabaseAlways<MyApplicationDbContext>
{
protected override void Seed(TitleDB context)
{
context.Products.Add(new Product { Id = 1, Name = "Foobar XL" });
context.Products.Add(new Product { Id = 2, Name = "Foobar LG" });
context.Products.Add(new Product { Id = 3, Name = "Foobar MD" });
context.SaveChanges();
base.Seed(context);
}
}
Upvotes: 1
Reputation: 21376
By default database initializer is set to DropCreateDatabaseIfModelChnages. you can set the database initializer to null to avoid recreating,
Database.SetInitializer<YourContext>(null);
The other option is to use Database Migrations to update database without recreating it.
Upvotes: 1