Mohamed Abdeen
Mohamed Abdeen

Reputation: 215

Get SQL file for specific migration in Entity Framework 6 C#

In Entity Framework 6, I need to get the SQL script for specific migration file and I already updated the database. I found that in update-database command I can add script parameter to export the migration to SQL, but I already updated the database. I found in Entity Framework Core, a command called Script-Migration with script name as an argument. Is there any similar command in Entity framework?

I also tried the suggestion "Update database command", but I got an empty SQL file.

Upvotes: 20

Views: 27131

Answers (5)

ElasticCode
ElasticCode

Reputation: 7875

The following generates a SQL script from the given migration to the latest migration using VS > Package Manager Console (Use the name of the migration before the last one to get only the latest migration script).

Script-Migration <PreviousMigrationName>

If have only one migration file, the following generates a SQL script from a blank database to the latest migration:

Script-Migration

Upvotes: 0

zappa
zappa

Reputation: 910

If you're now in .net core, use

Script-Migration -From <PreviousMigration> -To <LastMigration>

If you don't execute the last migration, you can run

Script-Migration -From <PreviousMigration>

Don't include the date/times preceeding the migration name. For example if the migration name in the database is: 20210209184835_add-parent-id-to-contract, then run the following in the package manager

Script-Migration -From add-parent-id-to-contract

Upvotes: 17

Pushpak
Pushpak

Reputation: 379

You can run the following command from Package manager console. It will generate a temporary file and will open it in VS:

Script-Migration

Upvotes: 1

ChW
ChW

Reputation: 3348

Yes, you could generate the migration-SQL as follows:

Update-Database -Script -SourceMigration: <pointFromWichYouWantToStartWithGeneration> -TargetMigration: <pointWhereToEndWithGeneration>

To create a script for all migrations execute the following:

Update-Database -Script -SourceMigration: $InitialDatabase

Instead of applying the changes to database it will generate a SQL script file. Therefore you could generate a SQL Script even if the migration was already applied to the database.

Here you could find some more information about it - Entity Framework Code First Migrations - Getting a SQL Script.

Run the Update-Database command but this time specify the –Script flag so that changes are written to a script rather than applied. We’ll also specify a source and target migration to generate the script for.

Upvotes: 32

user9603263
user9603263

Reputation: 61

If you want to generate -Script for migration N, you specify -SourceMigration N-1 (previous migration) and -TargetMigration N

Upvotes: 6

Related Questions