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

Database First - trying to recreate my entities that exist


I'm trying to connect my app to an existing Application. So i created the Entities with the Entity Framework Database First.

It create all my entities and my Context that's fine. But when i try to run it tell me that my migrations are not up-to-date so i tried to add-migration test to see what was missing...

It's creating all the table i asked it from DataBase First...

I cant recreate those tables i just want to be able to connect to those tables...

I absolutly need to connect to those tables, i cannot create a new one and i cannot clone the database.

How can i achieve this... i didnt find any resources on the subject that goes from the start to the end of the process.

Some help would be awesome!


Solution

  • The Problem: You can't reset migrations with existing tables in the database as EF wants to create the tables from scratch.

    What to do:

    Delete existing migrations from Migrations_History table.

    Delete existing migrations from the Migrations Folder.

    Run add-migration Reset. This will create a migration in your Migration folder that includes creating the tables (but it will not run it so it will not error out.)

    You now need to create the initial row in the MigrationHistory table so EF has a snapshot of the current state. EF will do this if you apply a migration. However, you can't apply the migration that you just made as the tables already exist in your database. So go into the Migration and comment out all the code inside the "Up" method.

    Now run update-database. It will apply the Migration (while not actually changing the database) and create a snapshot row in MigrationHistory.

    You have now reset your migrations and may continue with normal migrations.