Search code examples
c#entity-frameworkef-code-first

C# Code First there is already an object named xxx in the database when trying to Update-Database in PM Console


I deleted some tables thinking they would be recreated on running my application but they weren't and it said couldn't find table. So to rerun the migrations I've deleted them from the migration table. Now when I try update-database it says there is already object xxx in the database (different table to what I deleted)

I'm new to EF-Code First so any help gratefully appreciated :)


Solution

  • Its depending on your data, you want to keep them or no.

    1. You can entirely delete your database and recreate it using Update-Database command.
    2. You can modify your ConnectionString and create correct version of your corrupted database to manually add missing tables and relations.
    3. You can create the correct version of database as I said in 2 and move your existing records from corrupted database into the fresh version of your database using Generate Scripts (use this tutorial, and generate script only for data, not Schema).

    Things to note:

    • Entity-Framework keeps track of Tables, Relations, Constraints and Indexes so even an small change in them will make problems for you.
    • Entity-Framework keeps an snapshot of your database schema for every single migration.
    • Tweaking database needs you to be accurate and know what will happens if you do something.