Entity Framework won't detect changes of navigation properties

后端 未结 3 576
花落未央
花落未央 2020-12-16 14:42

I\'m having trouble with detecting changes of a navigation property:

My testing model looks like this:

public class Person
{
    public int Id { get;         


        
3条回答
  •  青春惊慌失措
    2020-12-16 15:07

    In my application, before a reload is requested or the user leaves the item/view, I perform some checks to make sure there are no unsaved changes.

    This is basically running off the currently accepted answer, but I wanted to provide an implementation and bring to the attention that you must call Context.ChangeTracker.DetectChanges() before the ObjectContext.ObjectStateManager can pick up relationship changes! I spent quite a bit of time debugging this, silly!

    _EagleContext.ChangeTracker.DetectChanges();
    
    var objectContext = ((IObjectContextAdapter)_EagleContext).ObjectContext;
    var changedEntities = objectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified);
    
    if (_EagleContext.ChangeTracker.Entries().Any(e => e.State == EntityState.Modified)
        || changedEntities.Count() != 0)
    {
        var dialogResult = MessageBox.Show("There are changes to save, are you sure you want to reload?", "Warning", MessageBoxButton.YesNo);
        if (dialogResult == MessageBoxResult.No)
        {
            return;
        }
    }
    
    // Continue with reloading...
    

提交回复
热议问题