Entity Framework 5 - DbContext Has Changes?

前端 未结 2 454
猫巷女王i
猫巷女王i 2020-12-14 00:52

I\'m trying to find a way to determine of any changes have been made to a database context (DbContext). Note: I\'m using Visual Studio 2012 with Entity Framework 5 on a Win

相关标签:
2条回答
  • 2020-12-14 01:12

    For EF 5 use DbContext's ChangeTracker:

     public bool HasUnsavedChanges()
     {
        return this.ChangeTracker.Entries().Any(e => e.State == EntityState.Added
                                                  || e.State == EntityState.Modified
                                                  || e.State == EntityState.Deleted);
     }
    

    For EF 6 use the ChangeTracker.HasChanges() method which will also detect changes in many to many relationships:

     public bool HasUnsavedChanges()
     {
        return this.ChangeTracker.HasChanges();
     }
    
    0 讨论(0)
  • 2020-12-14 01:30

    I know as you are using Entity Framework 5, this answer will not help you, but it may help others.

    Starting with Entity Framework 6 and in Entity Framework Core you can check for changes simply by following line of code:

    context.ChangeTracker.HasChanges()
    
    0 讨论(0)
提交回复
热议问题