Ian1971
Ian1971

Reputation: 3696

Script EF migration seed from Configuration class

I have EF migrations working nicely, but I also want to generate the sql script for the seed data from my DbMigrationsConfiguration class. The seed data runs ok when I do Update-Database, but when I do UpdateDatabase -Script I do not get the sql for the seed inserts. I tried -Verbose on a normal Update-Database but I do not see the seed statements output there either.

Is this possible?

Upvotes: 26

Views: 11115

Answers (3)

Tawab Wakil
Tawab Wakil

Reputation: 2313

Whether you are using EF or EF Core, a solution/workaround is to have SSMS generate the seed script for you:

  1. Start with a clean database generated by your DB initializer and seed method. Make sure the data you want scripted is in there.

  2. Using SSMS, right-click the database, go to Tasks > "Generate Scripts...", and follow the wizard. Under Advanced options, be sure to select "Data only" for "Types of data to script".

  3. From the generated script, copy required seed statements over to your target script.

Upvotes: 9

Maulik Patel
Maulik Patel

Reputation: 41

I know it's bit of an old thread but, here is an answer that could help someone else looking for an answer.

You can use the Migrate.exe supplied by Entity Framework. This will allow you to run the Seed method on the database context.

If you need to run a specific Seed method you can place that in a separate migration config file like this:

Enable-Migrations -MigrationsDirectory "Migrations\ContextA" -ContextTypeName MyProject.Models.ContextA

Command:

Migrate.exe MyAssembly CustomConfig /startupConfigurationFile=”..\web.config”

Look for it in the NuGet packages directory: "..\packages\EntityFramework.6.1.3\tools"

You can specify migration configuration as an argument to it. The CustomConfig should contain your code based Seed method. So, This way you do not require SQL scripts to be generated from the migration.

More info here:

http://www.eidias.com/blog/2014/10/13/initialcreate-migration-and-why-is-it-important

http://www.gitshah.com/2014/06/how-to-run-entity-framework-migrations.html

Using this solution, you do not need to generate an SQL script and can run multiple Seeds for different environments.

Upvotes: 4

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

No it is not possible. Configuration class is not part of migration itself - it is infrastructure executing the migration. You have single configuration class for all your migrations and its Seed method is executed after every migration run - you can even use context for seeding data and because of that this method is executed after the migration is completed = it cannot be part of migration. Only content of the migration class is scripted.

Upvotes: 20

Related Questions