Script EF migration seed from Configuration class

匿名 (未验证) 提交于 2019-12-03 01:49:02

问题:

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?

回答1:

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.



回答2:

Another solution/workaround is to have SSMS generate the 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.



回答3:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!