Pinch
Pinch

Reputation: 4207

How to force EF code first to recreate databases?

I had a bunch of tables Code First created.

Then in SQL i deleted one table so that i could inevitably ask this question on stack.

Upon using update-database in package management console I get:

Cannot find the object "dbo.ContractParents" because it does not exist or you do not have permissions.

What is the best way to recreate my table?

I've read up about context.Database.CreateIfNotExists();

I put it in my seed function, but nothing doing.

Thanks!

Upvotes: 16

Views: 24574

Answers (3)

Steve
Steve

Reputation: 1065

For yet another cheesy option...

Right click on your db in server explorer, and hit delete Then you can do

Enable-Migrations -EnableAutomaticMigrations -Force

Update-Database -Force

Dirty update, clean result :)

Upvotes: 8

ledgeJumper
ledgeJumper

Reputation: 3630

To explain what happens with your update-database command and why the context.Database.CreateIfNotExists() method in the seed did not work:

When you run the update-database command it first looks at your connection string to see if the database is there. If it is it looks at the migration history table and checks that against what is in you DbContext class. If it sees that there are tables missing or changes it will attempt to update the database. The Seed method is not called until after that is done, so that is why that did not work.

While developing using EF-Code First I usually approach the problem in a few different ways depending on how large my database is. I usually went the route of deleting all the tables (including the migration history table) and then running the update-database command again. Works fine, just really time consuming if you have a lot of tables with a lot of FK constraints on it.

I finally became tired of it and found these scripts to make the dropping of tables exponentially faster. I went to this because I was running my app on Azure. When I am running it on my local machine, I would just delete the whole database and make a brand new database with the same name.

Elegant solution? No. Does it work? More or less...

Upvotes: 11

Pinch
Pinch

Reputation: 4207

For a quick and dirty approach, that'll get you home for dinner on time along with lots of dataloss (i'm still in beta using test data)

drop the dbo.__MigrationHistory system table

along with all of your other tables.

Back up your data first!

update-database -verbose (you may need some sauce with your spaghetti)

I am not impressed, but it works.

Hopefully someone will come up with a better answer in the future.

It would help to really understand migrations better.

Upvotes: 4

Related Questions