问题描述
我是很新的实体框架(和asp.net MVC 3),这是我与EF4.1 code第一次真正第一次经历。
i'm quite new to Entity Framework (and asp.net mvc 3) and this is my really first experience with EF4.1 code first.
我的问题很简单:当我通过模型生成我想为数据库中的新表使
My question is simple: when I generate via model a new table for database I would like to make
- 自动当前日期时间创建一个新行时添加一个字段。
- 每场被更新时自动更新域。
其实,出现变量,如:
[DisplayName("Data Modifica")]
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime DataModifica { get; set; }
我想我可以写的datacontext的OnModelCreating事件的东西,但我太新已经掌握了这个:)
I guess i could write something on "OnModelCreating" event of datacontext but I'm too new to already master this :)
有人能帮助?
在此先感谢,
诉
thanks in advance,V.
推荐答案
这无关与创作模式。 模型是类和数据库之间的映射关系的描述。 OnModelCreating
用于修改映射定义,不修改数据。它无关,与在实体实例本身的数据。
That has nothing to do with creation of model. The "model" is description of your mapping between classes and database. OnModelCreating
is used to modify mapping definition, not to modify data. It has nothing to do with data in the entity instance itself.
如果你想自动修改你可以覆盖的SaveChanges
:
If you want automatic modification you can override SaveChanges
:
public override int SaveChanges()
{
DateTime now = DateTime.Now;
foreach (var entity in ChangeTracker.Entries<YourEntityType>()
.Where(e => e.State == EntityState.Added || e.State == EntityState.Modified)
.Select(e => e.Entity))
{
entity.DateModifica = now; // set the date
}
return base.SaveChanges();
}
这篇关于实体框架4.1自动日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!