Get all tracked entities from a DbContext?

前端 未结 3 1397
离开以前
离开以前 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:40

    I think you can use the ChangeTracker for this:

    public class MyContext : DbContext
    {
        //...
    
        public override int SaveChanges()
        {
            foreach (var dbEntityEntry in ChangeTracker.Entries())
            {
                dbEntityEntry.Entity.UpdateDates();
            }
            return base.SaveChanges();
    
        }
    }
    

提交回复
热议问题