15

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!

1
  • 3
    Migrations is not going to fix a mutilated database for you. It takes a database from a known state to a new known state. You'll have to recreate the table manually or create a whole new database. Oct 1, 2013 at 14:45

3 Answers 3

10

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...

0
8

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 :)

4

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.

3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.