7

StoreGeneratedPattern="Computed" works flawlessly on columns of type timestamp. But you can't display a TimeStamp as a human-readable form.

So you can't show the user "This row was modified on {TimeStamp}" because you simply can't parse a SQL Timestamp to DateTime.

Now can I also create computed columns for DateTime columns so I don't need to set it manually? myEntity.LastModification = DateTime.Now

Not to mention it would be quite error-prone, if some user really wanted to do something bad, by simply changing his computers time.

SeToY
  • 5,777
  • 12
  • 54
  • 94
  • What about triggers, if your techno is database first ? Or inheritance and custom action on save if you're using code first (but I don't think you do). By the way, is it a web app ? If yes, DateTime.Now will be your web server datetime, not the client's one. – Raphaël Althaus Dec 14 '12 at 09:32
  • @RaphaëlAlthaus It's a WPF application... And I think maintaining triggers next to the edmx Model is not really fancy. Then I'd just stick with assigning the `DateTime.Now` myself :p – SeToY Dec 14 '12 at 09:33
  • Ok. So model first ? Did you look at that : http://stackoverflow.com/questions/6029766/how-to-create-update-a-lastmodified-field-in-ef-code-first ? It's code first, but you could change the code generator to have your classes implementing the desired interfaces... – Raphaël Althaus Dec 14 '12 at 09:44

1 Answers1

1

Yes, as described here: Is there a way to specify default values for columns? Some DateTime columns in my database are set to getdate(), but the EF is unaware of these default values

Extract:

...If you set the StoreGeneratedPattern to Identity (if the value is only computed on insert) or Computed (if it is computed on every update), then when you call SaveChanges the EF will get the value generated in the database and bring it back to update your object...

EDIT: to make the DB server side Modification date updated, follow this answer https://stackoverflow.com/a/8461681/1679310. Computed setting will do the reload

Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • 1
    Well, I've checked this on Google before asking here, and setting my DateTime column to `Computed` doesn't change the column on inserting or updating at all. – SeToY Dec 14 '12 at 09:34
  • `Identity` isn't enough, because LastModification changes on (well...) every modification and not just on inserting. – SeToY Dec 14 '12 at 10:00
  • Oh, I see now, the Identity should work for Creation (you are right), as the link above shows, for Modification, you will need some trigger, to change that date... and then yes, `Computed` should work – Radim Köhler Dec 14 '12 at 10:02
  • So, you suggest just setting it to `Computed` and it will be triggered automatically by EF? Or do I still need to write a trigger for each and every table in my DB? – SeToY Dec 14 '12 at 10:05