0

I'm considering using the Code First approach with Entity Framework.

I like adding triggers to my SQL database on fields like DateAdded and DateModified so that they automatically update with a getdate() as required.

From what I hear this is difficult with EF: Code First, so is there an alternative?

Rowan Freeman
  • 15,724
  • 11
  • 69
  • 100
  • 1
    it's not fun. You would need to override your POCO's OnModelCreating and set the property to getdate – Dave Alperovich Mar 29 '13 at 17:15
  • @DaveA No, you can set `DatabaseGenerated.Computed`, but I think the OP refers to creating triggers by migrations, do you Rowan? – Gert Arnold Mar 29 '13 at 21:57
  • @GertArnold, I was thinking of using `DatabaseGenerated.Computed` in the `OnModelCreating` method. I assumed this was a replacement for triggers. Understanding that triggers are problematic in code-first – Dave Alperovich Mar 29 '13 at 22:26
  • Well my question is that I don't know how it should be done or how best it should be done. So I'm open to any suggestions. Would one way to do this be using code first migrations and simply add the triggers to the SQL server as I go? That would mean that if I move the project to another server and the code first generates the database then I will have to add the triggers all over again. What about instead of using triggers I simply alter my code so that `DateUpdated` is updated to current `GETDATE()` when that table is edited? Would that be best practice? – Rowan Freeman Mar 30 '13 at 04:52

1 Answers1

1

It doesn't have to be difficult (e.g. getdate() default), you just have to know where to inject...

You can include a custom SQL into the 'chain' - via using Seed-ing or custom Initializer - to do any kind of custom work.

You may have problems with migrations, if you want to do that 'post-creation' - but if you limit all such similar init work while the Db is still empty you should be ok.

Another thing to worry about is various Db providers - as any custom SQL may vary, or support - but if you know what you're targeting you should be ok.

Check this link - Possible to default DateTime field to GETDATE() with Entity Framework Migrations?
Or this one generally about Triggers https://stackoverflow.com/a/5913581/417747

...it might be close to what you need - and get you ideas about how to do some other things.

Community
  • 1
  • 1
NSGaga-mostly-inactive
  • 14,052
  • 3
  • 41
  • 51