Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework migrations - generate sql script of current database model

I am trying to generate sql script that will create a database for me. So far I tried this:

Update-Database -Script -SourceMigration: $InitialDatabase Update-Database -Script -SourceMigration:0 

But both of those are giving me scripts that are beggining from first migration to last. And there is no initial state of database, which should include creation of the database itself, and single table that was there when I added migrations to my project.

So how do I recreate my model now, when migrations aren't giving me full sql script?

like image 720
ojek Avatar asked Oct 02 '13 13:10

ojek


People also ask

Which command generate SQL script from migrations?

With From and To The following generates a SQL script from the specified from migration to the specified to migration. You can use a from that is newer than the to in order to generate a rollback script.

How do I code my first migration to an existing database?

Run the Add-Migration InitialCreate command in Package Manager Console. This creates a migration to create the existing schema. Comment out all code in the Up method of the newly created migration. This will allow us to 'apply' the migration to the local database without trying to recreate all the tables etc.


1 Answers

Try:

Update-Database -Script -SourceMigration: $InitialDatabase -TargetMigration: [MigrationName] 

That should include the script from the initial database to the migration targeted. At the very least should have the "MigrationHistory" table.

You can also try recreating your migrations by:

1) Reverting back to the initial database. If everything goes well, this should remove all the tables from your database.

Update-Database -TargetMigration: $InitialDatabase 

2) Delete all your migration file inside the Migrations folder. You don't have to delete the configuration class file.

3) Add a new migration. However, this would create a migration file from the initial database to your latest model.

Add-Migration -Name: [MigrationName] 

Hopefully this helps. I also suggest looking at this blog post. Take note of tip #5 which is "Never delete a Migration before backing it out (Down)". In my experience this causes issues with migration if not followed.

like image 83
cubski Avatar answered Sep 19 '22 15:09

cubski