一種解決方案是使用部分覆蓋您生成的entitycontext類。這將攔截所有的實體類的插入/更新您的EF方面:
public partial class MyEntities : ObjectContext
{
public override int SaveChanges(SaveOptions options)
{
this.DetectChanges();
foreach (var insert in this.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added))
{
if (insert.Entity.HasProperty("DateCreated"))
insert.Entity.GetType().GetProperty("DateCreated").SetValue(insert.Entity, DateTime.UtcNow, null);
if (insert.Entity.HasProperty("LastModified"))
insert.Entity.GetType().GetProperty("LastModified").SetValue(insert.Entity, DateTime.UtcNow, null);
}
foreach (var update in this.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified))
{
if (update.Entity.HasProperty("LastModified"))
update.Entity.GetType().GetProperty("LastModified").SetValue(update.Entity, DateTime.UtcNow, null);
}
return base.SaveChanges(options);
}
}
或者做類似的事情,找你的時間戳字段插入/更新,並從ObjectStateEntries集合中移除呢?
謝謝,我發佈之前嘗試過,但它不起作用。我正在使用VS 2010 Ultimate,SP1和EF4 – Rachel 2011-05-11 14:26:45
在這種情況下,請檢查在EDMX文件的CSDL和SSDL部分都設置了正確的商店生成模式(必須將其打開爲XML),因爲這是有效的方式。 – 2011-05-11 14:31:13
@Ladislav我正在給這個另一個嘗試,但是我得到關於一個不可空字段映射到可空實體屬性的錯誤。你知道它在說什麼嗎? – Rachel 2011-05-11 14:59:24