heymega
heymega

Reputation: 9391

EF Add Existing Table Without Migration

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.

Upvotes: 0

Views: 2224

Answers (2)

DrewJordan
DrewJordan

Reputation: 5314

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

Upvotes: 0

Miroslav Holec
Miroslav Holec

Reputation: 3217

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.

Upvotes: 1

Related Questions