Reputation: 5704
In my Entity Framework Code First project, if I run the
update-database
command through the Package Manage Console, my Seed()
method runs successfully. If, however, I run the command with the -script parameter:
update-database -script
...the Seed() method is not called and the resulting SQL does not contain the SQL commands for seeding the database. 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?
Upvotes: 1
Views: 1365
Reputation: 4359
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. 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.
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. Imagine that you have a Seed()
method like this:
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. How would you try to compile that to 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 (i.e. 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.
Upvotes: 1