If my model changes, how do I rebuild the database in EF?

.net c# entity-framework

Question

I did this while creating a DbContext:

   public class myDB : DbContext
   {
     public DbSet<Party> Parties { get; set; }
     public DbSet<Booking> Bookings { get; set; }
   }

This produced the two tables above as well as my database. Great

When I added a second DbSet, I received the following error:

the model backing the 'Party' context has changed since the database was created

I understand how to solve this usingmodelbuilder.IncludeMetadataInDatabase = false; and Database.SetInitializer<ClubmansGuideDB>(null);

1) How should I add my new classes to the context so that the DataBase can produce them?

2) I removed the tables and attempted to re-run the program without success. I then deleted the whole database and tried to re-run, but it doesn't re-generate the DB. I need to start again, but is there a cache somewhere?

1
5
1/9/2012 7:00:14 PM

Accepted Answer

I think what you're searching for is

Database.SetInitializer<ClubmansGuideDB>(new DropCreateDatabaseIfModelChanges<ClubmansGuideDB>());

EF 4.1 and later, as of.

It should be noted that this presupposes you have authorization to even dump your database. To make development easier locally, I use this, but I deactivate it in staging and production (I do a manual Schema Compare and push my changes).

By the way, if you need to forcibly rebuild the database for testing, you may perform the following:

using (var context = new ClubmansGuideDB()) {
    context.Database.Initialize(force: true);
}

(using if your database doesn't already contain a reference)

15
1/9/2012 6:24:40 PM

Popular Answer

You may use a to instruct the Entity Framework to completely reconstruct the database.Database Initializer alternatively you may check out the First Migrations Code if you wish to move data.

When the model changes, the following would rebuild your database:

Database.SetInitializer<myDB>(new DropCreateDatabaseIfModelChanges<myDB>());


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow