Prescott
Prescott

Reputation: 7412

EntityFramework code-first, run a database update script after DropCreate

I'm trying to find some nice work arounds for the issues of computed columns in code first. Specifically, I have a number of CreatedAt datetime columns that need to be set to getdate().

I've looked at doing this via the POCO constructors, but to do that I must remove the Computed option (or it won't persist the data), however, there is no easy to way ensure the column is only set if we are inserting a record. So this would overwrite the CreatedAt each time we update.

I'm looking to create an alter script that can be called after the DropCreate that would go through and alter various columns to include the default value of getdate().

  1. Is there an event to hook into something like OnDropCreateCompleted where I could then run additional SQL
  2. What would be the best way handle the alter script? I am thinking just sending raw sql to the server that would run.
  3. Is there another way to handle the getdate() issue that might be more graceful and more inline with code first that I'm missing?

Thanks

Upvotes: 1

Views: 1056

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364249

You can just make custom initializer derived from your desired one and override Seed method where you can execute any SQL you want to use - here is some example for creating such initializer.

If you are using migrations you can just the custom SQL to Up method.

Upvotes: 2

Related Questions