简体   繁体   中英

Using computed DateTime columns in Entity Framework

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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