Generate full SQL script from EF 5 Code First Migr

2019-01-09 23:57发布

问题:

How do I use Entity Framework 5 Code First Migrations to create a full database script from the initial (empty) state to the latest migration?

The blog post at MSDN Blog suggests to do this, but it seems to create an empty script:

Update-Database -Script -SourceMigration: $InitialDatabase

回答1:

The API appears to have changed (or at least, it doesn't work for me).

Running the following in the Package Manager Console works as expected:

Update-Database -Script -SourceMigration:0


回答2:

To add to Matt wilson's answer I had a bunch of code-first entity classes but no database as I hadn't taken a backup. So I did the following on my Entity Framework project:

Open Package Manager console in Visual Studio and type the following:

Enable-Migrations

Add-Migration

Give your migration a name such as 'Initial' and then create the migration. Finally type the following:

Update-Database

Update-Database -Script -SourceMigration:0

The final command will create your database tables from your entity classes (provided your entity classes are well formed).