3

Using Entity Framework CodeFirst, how do I create a created datetime column that gets populated with the current timestamp everytime a record is inserted for that table, and a modified datetime column that has a timestamp generated evertime a row is updated? Rails does this by default and I was hoping the EF generated database would have this as well, but it doesn't. Is this something that can be done with data annotations? If so, how?

Thanks!

Tyler Jones
  • 1,283
  • 4
  • 18
  • 38

1 Answers1

4

It is not supported in EF. EF will not create these columns for you automatically. You must do it yourselves by either:

  • Have Created and Modified properties in every entity where you want to maintain these values. You must also manually maintain these columns in your application (common approach is overriding SaveChanges and set values accordingly).
  • If you don't need these values mapped (you never expect to use them in your application and you are happy with the logic in the database) you can create custom database initializer which would execute your custom SQL to alter tables and add those columns, default constraints for Created columns and update triggers for Modified columns.
Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Pefect! Thank you! Just to be clear, though, there's no way to accomplish this with data annotations? – Tyler Jones Jan 08 '12 at 22:40
  • 1
    No because data annotations do not add additional logic to maintain value in the those properties and currently EF don't allow you adding custom annotations. – Ladislav Mrnka Jan 08 '12 at 22:41