实体框架/ SQL2008-如何自动更新实体的LastModified字段?

如果我有以下实体:


public class PocoWithDates

{

   public string PocoName { get; set; }

   public DateTime CreatedOn { get; set; }

   public DateTime LastModified { get; set; }

}

对应于具有相同名称/属性的SQL Server 2008表...


我如何自动:


将记录的CreatedOn / LastModified字段设置为现在(执行INSERT时)

将记录的LastModified字段设置为现在(执行UPDATE时)

当我自动说时,我的意思是我希望能够做到这一点:


poco.Name = "Changing the name";

repository.Save(); 

不是这个:


poco.Name = "Changing the name";

poco.LastModified = DateTime.Now;

repository.Save();

在幕后,“某物”应自动更新日期时间字段。那是什么“东西”?


我正在使用Entity Framework 4.0-EF是否可以为我自动执行此操作?(也许是EDMX中的特殊设置?)


从SQL Server方面,我可以使用DefaultValue,但这仅适用于INSERT(而不是UPDATE)。


同样,我可以在POCO上使用构造函数设置默认值,但是同样,这仅在实例化对象时有效。


当然,我可以使用触发器,但这并不理想。


因为我使用的是Entity Framework,所以我可以在这里挂入SavingChanges事件并更新日期字段,但是问题是我需要“意识到” POCO(目前,我的存储库已使用泛型实现)。我将需要进行某种OO欺骗(例如使我的POCO实现一个接口,并在该接口上调用一个方法)。我对此并不反对,但是如果我必须这样做,我宁愿手动设置字段。


我基本上是在寻找SQL Server 2008或Entity Framework 4.0解决方案。(或智能.NET方式)


有任何想法吗?


慕桂英3389331
浏览 654回答 3
3回答

holdtom

我知道我参加聚会有点晚了,但是我只是为我正在从事的项目解决了这个问题,并认为我会分享我的解决方案。首先,为了使解决方案更可重用,我创建了带有timestamp属性的基类:public class EntityBase{&nbsp; &nbsp; public DateTime? CreatedDate { get; set; }&nbsp; &nbsp; public DateTime? LastModifiedDate { get; set; }}然后我覆盖了DbContext上的SaveChanges方法:public class MyContext : DbContext{&nbsp; &nbsp; public override int SaveChanges()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; ObjectContext context = ((IObjectContextAdapter)this).ObjectContext;&nbsp; &nbsp; &nbsp; &nbsp; //Find all Entities that are Added/Modified that inherit from my EntityBase&nbsp; &nbsp; &nbsp; &nbsp; IEnumerable<ObjectStateEntry> objectStateEntries =&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; from e in context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; where&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.IsRelationship == false &&&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.Entity != null &&&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; typeof(EntityBase).IsAssignableFrom(e.Entity.GetType())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; select e;&nbsp; &nbsp; &nbsp; &nbsp; var currentTime = DateTime.Now;&nbsp; &nbsp; &nbsp; &nbsp; foreach (var entry in objectStateEntries)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var entityBase = entry.Entity as EntityBase;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (entry.State == EntityState.Added)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; entityBase.CreatedDate = currentTime;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; entityBase.LastModifiedDate = currentTime;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return base.SaveChanges();&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP