EF CodeFirst:Rails样式的创建和修改列 [英] EF CodeFirst: Rails-style created and modified columns

查看:67
本文介绍了EF CodeFirst:Rails样式的创建和修改列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Entity Framework CodeFirst,我如何创建一个创建的datetime列,该列在每次为该表插入记录时填充当前时间戳,而修改后的datetime列则在每次更新一行时生成时间戳。 Rails默认情况下会这样做,而我希望EF生成的数据库也可以这样做,但事实并非如此。这可以通过数据注释来完成吗?

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?

谢谢!

推荐答案

不是吗?在EF中受支持。 EF不会自动为您创建这些列。您必须自己进行以下操作:

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


  • 具有已创建和<$ c $您要维护这些值的每个实体中的c> Modified 属性。您还必须在应用程序中手动维护这些列(常用方法正在覆盖 SaveChanges 并相应地设置值)。

  • 如果您不需要映射这些值(您从不希望在应用程序中使用它们,并且对数据库中的逻辑感到满意),则可以创建自定义数据库初始化程序,它将执行您的自定义SQL来更改表并添加这些列,默认约束为创建列,并更新已修改列的触发器。

  • 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.

这篇关于EF CodeFirst:Rails样式的创建和修改列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆