How to force EF code first to recreate databases?

asp.net-mvc c# ef-code-first entity-framework

Question

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
14
10/2/2013 2:28:49 PM

Accepted Answer

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

9
10/1/2013 4:56:21 PM

Popular Answer

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



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