Entity Framework 5 - DbContext Has Changes?

青春壹個敷衍的年華 提交于 2019-11-27 12:46:18

问题


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 Windows 7, 64-bit box.

Back when I used to use ObjectContext instead of DbContext, I could do something like:

public partial class MyObjectContext
{
    public Boolean HasUnsavedChanges()
    {
        return (this.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted).Any());
    }
}

Now that I'm using DbContext, I tried to do this:

public partial class MyDbContext
{
    public ObjectContext ObjectContext()
    {
        return (this as IObjectContextAdapter).ObjectContext;
    }

    public Boolean HasUnsavedChanges()
    {
        return (this.ObjectContext().ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted).Any());
    }
}

The problem that I'm having is that the method "HasUnsavedChanges()" always return "false" even when I know for a fact that the context has been changed. Does anyone have any ideas as to what I'm doing wrong?


回答1:


You should use the DbContext's ChangeTracker:

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



回答2:


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 you can check for changes simply by following line of code:

context.ChangeTracker.HasChanges()


来源:https://stackoverflow.com/questions/12012607/entity-framework-5-dbcontext-has-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!