0

In EF, if I add a new entity which represents an existing table in the database I get an error stating I need to run a migration.

Is there anyway to add an existing table to my context without needing to create a new migration?

Seems pointless to have an empty migration like this...

public override void Up() { } public override void Down() { } 

I'm guessing every time I add entites it compares it to a serialised version in __MigrationHistory's model column.

2
  • so, the database table is there already? is there already a DbSet for the type mapped to the correct table? Commented Aug 24, 2015 at 9:30
  • Yes the table already exists - Ive just added the Dbset to my context which is throwing the migration error. Commented Aug 24, 2015 at 9:32

2 Answers 2

1

You have two choices in general:

  1. You can create your table in database and use it by your own way. That means, you can create for example Logs table and write data using standard SQL provider. If you will add this table later to you DbContext, migration will be created.
  2. You can create your database first and then write your code. This approach is called Reverse Engineering. You have still all advantages from code first approach but no migrations are created.

Another possible solution is have two DbContexts. In the first case you can use code first with migrations and the second could be DbContext used with reverse engineering way.

If you dont want to create migration whenever some change in your schema occurs, you can consider MigrateDatabaseToLatestVersion initialiser.

Sign up to request clarification or add additional context in comments.

Comments

0

What we've done in this scenario is re-use the latest migration. You can rescaffold a migration by using the -force switch and specifying the target migration. Make a copy of the current migration first to compare it after the force: you're essentially telling EF that it's OK to overwrite that file with whatever changes are pending. Here's the process:

  1. Update database to your second-most current migration. This will release the most current one for changes.

update-database -target:"SecondMostCurrentMigration"

  1. re-scaffold the most current migration using the existing file

add-migration MostCurrentMigrationName -force

  1. review the file against the copy you made to make sure nothing changed

  2. Update the database to the most current migration, the existing file that you just 'modified'.

update-database

1 Comment

Consider that with this approach you risk to lose table data. if your "down" from MostCurrentMigration contains something else, because probably it will drop other added tables or fields.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.