How to re-create database for Entity Framework?

121,397

Solution 1

Follow below steps:

1) First go to Server Explorer in Visual Studio, check if the ".mdf" Data Connections for this project are connected, if so, right click and delete.

2 )Go to Solution Explorer, click show All Files icon.

3) Go to App_Data, right click and delete all ".mdf" files for this project.

4) Delete Migrations folder by right click and delete.

5) Go to SQL Server Management Studio, make sure the DB for this project is not there, otherwise delete it.

6) Go to Package Manager Console in Visual Studio and type:

  1. Enable-Migrations -Force
  2. Add-Migration init
  3. Update-Database

7) Run your application

Note: In step 6 part 3, if you get an error "Cannot attach the file...", it is possibly because you didn't delete the database files completely in SQL Server.

Solution 2

I would like to add that Lin's answer is correct.

If you improperly delete the MDF you will have to fix it. To fix the screwed up connections in the project to the MDF. Short answer; recreate and delete it properly.

  1. Create a new MDF and name it the same as the old MDF, put it in the same folder location. You can create a new project and create a new mdf. The mdf does not have to match your old tables, because were going to delete it. So create or copy an old one to the correct folder.
  2. Open it in server explorer [double click the mdf from solution explorer]
  3. Delete it in server explorer
  4. Delete it from solution explorer
  5. run update-database -force [Use force if necessary]

Done, enjoy your new db

UPDATE 11/12/14 - I use this all the time when I make a breaking db change. I found this is a great way to roll back your migrations to the original db:

  • Puts the db back to original
  • Run the normal migration to put it back to current

    1. Update-Database -TargetMigration:0 -force [This will destroy all tables and all data.]
    2. Update-Database -force [use force if necessary]

Solution 3

This worked for me:

  1. Delete database from SQL Server Object Explorer in Visual Studio. Right-click and select delete.
  2. Delete mdf and ldf files from file system - if they are still there.
  3. Rebuild Solution.
  4. Start Application - database will be re-created.

Solution 4

While this question is premised by not caring about the data, sometimes maintenance of the data is essential.

If so, I wrote a list of steps on how to recover from Entity Framework nightmare when the database already has tables with the same name here: How to recover from Entity Framework nightmare - database already has tables with the same name

Apparently... a moderator saw fit to delete my post so I'll paste it here:

How to recover from Entity Framework nightmare - database already has tables with the same name

Description: If you're like us when your team is new to EF, you'll end up in a state where you either can't create a new local database or you can't apply updates to your production database. You want to get back to a clean EF environment and then stick to basics, but you can't. If you get it working for production, you can't create a local db, and if you get it working for local, your production server gets out of sync. And finally, you don't want to delete any production server data.

Symptom: Can't run Update-Database because it's trying to run the creation script and the database already has tables with the same name.

Error Message: System.Data.SqlClient.SqlException (0x80131904): There is already an object named '' in the database.

Problem Background: EF understands where the current database is at compared to where the code is at based on a table in the database called dbo.__MigrationHistory. When it looks at the Migration Scripts, it tries to reconsile where it was last at with the scripts. If it can't, it just tries to apply them in order. This means, it goes back to the initial creation script and if you look at the very first part in the UP command, it'll be the CreeateTable for the table that the error was occurring on.

To understand this in more detail, I'd recommend watching both videos referenced here: https://msdn.microsoft.com/en-us/library/dn481501(v=vs.113).aspx

Solution: What we need to do is to trick EF into thinking that the current database is up to date while not applying these CreateTable commands. At the same time, we still want those commands to exist so we can create new local databases.

Step 1: Production DB clean First, make a backup of your production db. In SSMS, Right-Click on the database, Select "Tasks > Export Data-tier application..." and follow the prompts. Open your production database and delete/drop the dbo.__MigrationHistory table.

Step 2: Local environment clean Open your migrations folder and delete it. I'm assuming you can get this all back from git if necessary.

Step 3: Recreate Initial In the Package Manager, run "Enable-Migrations" (EF will prompt you to use -ContextTypeName if you have multiple contexts). Run "Add-Migration Initial -verbose". This will Create the initial script to create the database from scratch based on the current code. If you had any seed operations in the previous Configuration.cs, then copy that across.

Step 4: Trick EF At this point, if we ran Update-Database, we'd be getting the original error. So, we need to trick EF into thinking that it's up to date, without running these commands. So, go into the Up method in the Initial migration you just created and comment it all out.

Step 5: Update-Database With no code to execute on the Up process, EF will create the dbo.__MigrationHistory table with the correct entry to say that it ran this script correctly. Go and check it out if you like. Now, uncomment that code and save. You can run Update-Database again if you want to check that EF thinks its up to date. It won't run the Up step with all of the CreateTable commands because it thinks it's already done this.

Step 6: Confirm EF is ACTUALLY up to date If you had code that hadn't yet had migrations applied to it, this is what I did...

Run "Add-Migration MissingMigrations" This will create practically an empty script. Because the code was there already, there was actually the correct commands to create these tables in the initial migration script, so I just cut the CreateTable and equivalent drop commands into the Up and Down methods.

Now, run Update-Database again and watch it execute your new migration script, creating the appropriate tables in the database.

Step 7: Re-confirm and commit. Build, test, run. Ensure that everything is running then commit the changes.

Step 8: Let the rest of your team know how to proceed. When the next person updates, EF won't know what hit it given that the scripts it had run before don't exist. But, assuming that local databases can be blown away and re-created, this is all good. They will need to drop their local database and add create it from EF again. If they had local changes and pending migrations, I'd recommend they create their DB again on master, switch to their feature branch and re-create those migration scripts from scratch.

Solution 5

Just want to add to the excellent answer of @Lin:

5) B. If you don't have SQL Management Studio, go to "SQL Server Object Explorer". If you cannot see your project db in the localdb "SQL Server Object Explorer", then click on "Add SQL server" button to add it to the list manually. Then you can delete the db from the list.

Share:
121,397

Related videos on Youtube

Toby Sharp
Author by

Toby Sharp

Updated on November 01, 2020

Comments

  • Toby Sharp
    Toby Sharp over 3 years

    I have got into a bad state with my ASP.Net MVC 5 project, using Code-First Entity Framework. I don't care about losing data, I just want to be able to start fresh, recreate the database and start using Code-First migrations.

    Currently I am in a state where every attempt to Update-Database results in an exception being thrown or getting an error message. Also the website can't access the database correctly. How can I wipe all migrations, re-create the database and start from scratch without having to create a new project? In other words, I want to keep my code but drop the database.

    Later I will also want to get the deployment database (SQL Server on Azure) in sync. Again, I don't mind dropping all the data - I just want to get it working.

    Please provide any how-to steps to get back to a clean state. Much appreciated.

    • Worthy7
      Worthy7 almost 8 years
      TBH if you simple want to DROP DATABASE then....
  • Toby Sharp
    Toby Sharp over 10 years
    Excellent! This worked, thank you! Very helpful indeed. Are the steps similar for re-creating the deployment database (Azure SQL)?
  • Lin
    Lin over 10 years
    hi @TobySharp, no problems. If you don't have any data in your database, you can follow these steps, but if you do have data, the steps are not quite the same.
  • Toby Sharp
    Toby Sharp over 10 years
    I don't have any data that I need to keep.
  • Mike Ward
    Mike Ward about 10 years
    Tried this. Doesn't work. step 6, part 3 says it cannot attach the file. And yes, I checked, no database connections are active. :(
  • Mike Ward
    Mike Ward about 10 years
    Update, if you delete from VS (as the instructions say) and not Windows Explorer, then it works. Also, if you don't have SQL Management Studio, you can use Sql Object Explorer in VS to delete from a localdb.
  • guitarlass
    guitarlass almost 10 years
    hi, im in the same situation and i got this 'cannot attach database' error. i followed all steps as stated but only thing my Sql Object Explorer doesn't show any database to delete. and i don't have sql management studio. please helpp
  • John Odom
    John Odom over 9 years
    Is it possible to re-create the database with the existing migration files?
  • Steve Coleman
    Steve Coleman over 9 years
    Great glad to help... I am going to update my answer. I recently found a better way to rollback all changes.
  • rluks
    rluks about 9 years
    @MikeWard "use Sql Object Explorer in VS to delete from a localdb" - allright, but there is a hierarchy SQL Server - (localdb) - Databases - ... how do I recognize which db to delete?
  • Andy
    Andy almost 9 years
    If you are getting the "Cannot attach file..." error, even though you believe you've deleted everything, try the answer from this thread: stackoverflow.com/questions/13275054/…
  • Oliver
    Oliver almost 9 years
    If you want to add something to an answer, please add a comment to that answer rather than posting a new answer.
  • Oliver
    Oliver almost 9 years
    I wasn't aware of that. So now you can move your answer into a comment and delete this answer since technically it is not an (complete) answer to the question :-)
  • aggie
    aggie over 8 years
    @Lin I need to merge two DB's how can I modify this to do the same.
  • aggie
    aggie over 8 years
    @Lin Thanks for the link, it shows multiple DbContext, but not how to merge them, do you know how to merge one schema into another?
  • Dan Bechard
    Dan Bechard over 7 years
    Yeah, all I had to do was delete the MDF, update the connection string in the web.config, then run the application and register a new account. It created all of the tables again in the new database automagically.
  • vmassuchetto
    vmassuchetto about 7 years
    Instead of step (5), I did the commands: sqllocaldb p mssqllocaldb; sqllocaldb delete mssqllocaldb
  • naz786
    naz786 over 6 years
    I get the error message "project [project_name] failed to build"
  • Przemysław Głębocki
    Przemysław Głębocki almost 3 years
    Updated Answer is much simpler! Thanks! Put it on top of your answer ;)