Entity Framework: Setting update timestamp

前端 未结 4 1547
囚心锁ツ
囚心锁ツ 2020-12-29 13:14

All of our database tables have UpdateUserID and UpdateTS. I\'d like to have this set if my entity has changes. Is there a way I can have this update on the spot condition

4条回答
  •  遥遥无期
    2020-12-29 13:35

    I call this extension method before calling context.SaveChanges():

    public static void SetLastModified(this ObjectContext context, DateTime dateTime)
    {
        DateTime now = DateTime.UtcNow;
        foreach (ObjectStateEntry entry in context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified))
        {
            if (!entry.IsRelationship)
            {
                IHasLastModified lastModified = entry.Entity as IHasLastModified;
                if (lastModified != null)
                    lastModified.LastModified = now;
            }
        }
    }
    

    I can easily call this code, because I've wrapper the ObjectContext in a repository class. If you're using it bare, you can hook up the ObjectContext.SavingChanges event to do something similar.

提交回复
热议问题