将EntatedDate添加到实体使用Entity Framework 5 Code First [英] Adding CreatedDate to an entity using Entity Framework 5 Code First

查看:139
本文介绍了将EntatedDate添加到实体使用Entity Framework 5 Code First的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向我的模型中的实体添加一个 CreatedDate 属性,并使用EF5 Code First。我希望这个日期不会被改变一次设置,我希望它是一个UTC的日期。我不想使用构造函数,因为我在我的模型中有很多实体,我想继承自包含 CreatedDate 属性的抽象类,我无法强制执行一个具有接口的构造函数。

I am trying to add a CreatedDate property to entities in my Model and am using EF5 Code First. I want this date to not be changed once set, I want it to be a UTC date. I do NOT want to use a constructor, as I have many entities in my model that I want to inherit from an abstract class containing the CreatedDate property, and I can't enforce a constructor with an interface.

我尝试过不同的数据注释,并尝试编写一个数据库初始化程序,它可以选择一个特定的实体类型并写入一个alter约束一个 getdate()正确的 table_name column_name ,但我无法正确编写该代码。

I have tried different data annotations and I have attempted to write a database initializer that would pick up a specific entity type and write an alter constraint with a getdate() default value for the correct table_name and column_name, but I have not been able to write that code correctly.

请不要将我引用到 AuditDbContext - 实体框架审核上下文 EntityFramework.Extended 工具,因为他们不会在这里做我需要的。

Please do not refer me to the AuditDbContext - Entity Framework Auditing Context or the EntityFramework.Extended tools, as they do not do what I need here.

更新

我的 CreatedDate SaveChanges()我传递一个ViewModel到我的视图,它正确地没有被称为 CreatedDate 的审计属性。即使我将模型传递给我,我也不会在视图中编辑或存储 CreatedDate

My CreatedDate is null on SaveChanges() because I am passing a ViewModel to my view, which correctly has no audit property called CreatedDate in it. And even if I passed the model to my view, I am not editing or storing the CreatedDate in the view.

我阅读了这里,我可以添加 [DatabaseGenerated( DatabaseGeneratedOption.Identity)] ,这将告诉EF在插入和更新后正确存储 CreatedDate ,但不允许我的应用程序更改:但是我只是得到一个通过添加此属性将IDENTITY_INSERT设置为OFF 错误时,无法在表中插入标识列的显式值。

I read here that I could add the [DatabaseGenerated(DatabaseGeneratedOption.Identity)] and this would tell EF to store the CreatedDate correctly after Insert and Update, but not allow it to be changed by my application: but I just get a Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF error by adding this attribute.

我将要切换到EF Model First,因为这个简单的数据库要求在Code First中实现是荒谬的。

I am about to switch to EF Model First because this simple database requirement is ridiculous to implement in Code First.

推荐答案

p>这是我如何做的:

Here is how I did it:

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime CreatedDate{ get; set; }

AddColumn("Agents", "CreatedDate", n => n.DateTime(nullable: false, defaultValueSql: "GETUTCDATE()"));

这篇关于将EntatedDate添加到实体使用Entity Framework 5 Code First的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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