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!
Ladislav Mrnka
It is not supported in EF. EF will not create these columns for you automatically. You must do it yourselves by either:
- Have
Created
andModified
properties in every entity where you want to maintain these values. You must also manually maintain these columns in your application (common approach is overridingSaveChanges
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 forModified
columns.
来源:https://stackoverflow.com/questions/8772566/ef-codefirst-rails-style-created-and-modified-columns