我应该如何使用 EF 4.1 注释 CreatedOn 和 ModifiedOn 列?
在我们的数据库中,每个表都有两个 DateTime 列,CreatedOn 和 ModifiedOn,通过 SQL Server 中的触发器设置。 CreatedOn 在 INSERT 上设置,ModifiedOn 在 INSERT 和 UPDATE 上设置。
我正在尝试使用实体框架 4.1。 我应该如何注释/配置这两个属性?
我认为它涉及注释[DatabaseGenerate(DatabaseGenerateOption.Compulated)]
,但是我应该对这两个属性都使用该注释,还是应该我在 CreatedOn 字段上设置了 [DatabaseGenerate(DatabaseGenerateOption.Identity)]
吗?
根据 MSDN Identity 只是意味着插入行时数据库会生成一个值。
,这在这里似乎是正确的。
另外,我应该使用[Timestamp]
吗?
In our database, every table has two DateTime columns, CreatedOn and ModifiedOn, set via triggers in SQL Server. CreatedOn is set on INSERT, and ModifiedOn is set on INSERT and UPDATE.
I am trying to use Entity Framework 4.1. How should I annotate/configure the two properties?
I think it involves the annotation [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
, but should I use that annotation for both, or should I set [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
on the CreatedOn field?
According to MSDN Identity simply implies that The database generates a value when a row is inserted.
, which seems true here.
Also, should I use [Timestamp]
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对
CreatedOn
使用Identity
,对ModifiedOn
使用Compulated
。Identity
表示该值仅在插入期间设置并返回给应用程序。Compated
在每次修改(包括插入)期间设置,并且在每次执行插入或更新后将值返回给应用程序。请注意,这些属性都不能在应用程序中设置。计算列也不能成为主键或外键的一部分(这不是您的情况)。
这仅适用于现有数据库。使用代码优先时,只能为
timestamp
或rowversion
设置Compulated
。Timestamp
用于乐观并发。如果将列标记为时间戳,则每次更新都将包含条件WHERE timestampColum = @lastKnownValue
。仅当最后一个已知值与当前值相同时,它才会更新记录。如果值不同,您将得到异常。它通常与timestamp
SQL 类型一起使用。将其与datatime
一起使用需要一些测试。 SQL datatime 的值与 .NET 中的值不同。Use
Identity
forCreatedOn
andComputed
forModifiedOn
.Identity
means that value is set only during insert and returned back to application.Computed
is set during each modification (including insert) and value is returned back to the application after each executed insert or update.Just be aware that neither of these properties can be set in the application. Computed columns also can't be part of primary key or foreign key (it will not be your case).
This will only work with existing database. When using code-first
Computed
can be set only fortimestamp
orrowversion
.Timestamp
is used for optimistic concurrency. If you mark a column as timestamp each update will contain conditionWHERE timestampColum = @lastKnownValue
. It will update the record only if last known value is the same as current value. If the value is different you will get an exception. It is usually used withtimestamp
SQL type. Using it withdatatime
would require some tests. Value of SQL datatime is not the same as value in .NET.