简体   繁体   English

EF代码优先update-database -script未运行Seed()方法

[英]EF Code First update-database -script not running Seed() method

In my Entity Framework Code First project, if I run the 在我的Entity Framework Code First项目中,如果我运行

update-database

command through the Package Manage Console, my Seed() method runs successfully. 通过Package Manage Console命令,我的Seed()方法成功运行。 If, however, I run the command with the -script parameter: 但是,如果我使用-script参数运行命令:

update-database -script

...the Seed() method is not called and the resulting SQL does not contain the SQL commands for seeding the database. ...没有调用Seed()方法,并且生成的SQL不包含用于播种数据库的SQL命令。 This behaviour is repeatable. 此行为是可重复的。 I'm attempting to create a full DB Script for deployment. 我正在尝试创建完整的数据库脚本以进行部署。

Why is there a discrepancy between the SQL Commands run with -script and without it, and how can I get update-database to run the Seed() method when using the -script switch? 为什么使用-script和不使用-script的SQL命令之间存在差异,以及如何使用-script开关获取update-database以运行Seed()方法?

I would argue that this is not a discrepancy, but a by design feature. 我认为这不是差异,而是设计使然。

For one, when you use -script , the database update is not performed, so the Seed() method should not be called either. 例如,当您使用-script ,不会执行数据库更新,因此也不应该调用Seed()方法。 And also there is the fact the migrations is a design time tool, and Seed() is a method that has be compiled and called at runtime. 还有一个事实是,迁移是一种设计时工具,而Seed()是一种已在运行时进行编译和调用的方法。

And as for why isn't the contents of the Seed() method included in the generated script, my answer is also the different notions of runtime and design time . 至于为什么生成的脚本中不包含Seed()方法的内容,我的答案也是运行时设计时间的不同概念。 Imagine that you have a Seed() method like this: 想象一下,您有如下的Seed()方法:

protected override void Seed(PersonContext context)
{
   Random r = new Random();
   context.People.Add(new Person("PersonA", r.Next(90));
   context.SaveChanges();
}

Now the Random instance is created at runtime, and the Next() is called at runtime. 现在,在运行时创建Random实例,并在运行时调用Next()。 How would you try to compile that to SQL? 您将如何尝试将其编译为SQL? What if you have a file and you read data from it and put that into the database? 如果您有一个文件并从中读取数据并将其放入数据库,该怎么办? These are all things that cannot be evaluated at design time, only at runtime (ie if the file is not at the right place at design time, it's not a problem, only at runtime). 这些都是在设计时无法仅在运行时进行评估的事情(即,如果文件在设计时不在正确的位置,则仅在运行时没有问题)。 And that's why a design time tool like the migration scaffolder cannot evaluate it. 这就是为什么诸如迁移脚手架之类的设计时工具无法对其进行评估的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM