Get all tracked entities from a DbContext?

前端 未结 3 1394
离开以前
离开以前 2021-02-04 02:50

Many of the tables in my database need to have a \"DateCreated\" and \"DateModified\" column. I want to update these columns whenever SaveChanges() is called.

3条回答
  •  误落风尘
    2021-02-04 03:54

    This has worked well in our project so we don't have to remember to override something every time we add a new entity that has our standard LastUpdatedDateTime property. Using EF4; for an EF5 DbContext I think ((IObjectContextAdapter)_dbContext).ObjectContext.ObjectStateManager would get you the object state manager:

    // In our SaveChanges wrapper:
            var entries = context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted);
    
            private static void PopulateDate(IEnumerable entries)
                    {
                        foreach (var entry in entries)
                        {
                            if (entry.State != EntityState.Deleted)
                            {
                                if ((entry.Entity != null) && (entry.Entity.GetType().GetProperty("LastUpdatedDateTime") != null))
                                {
                                    ((dynamic)entry.Entity).LastUpdatedDateTime = DateTime.UtcNow;
                                }
                            }
                        }
                    }
    

    The reflection call is not an issue: for an object with 25 properties (alot), a million reflection queries takes an avg ~210 ms.

提交回复
热议问题