Detect whether DataContext has changes RRS feed

  • Question

  • Hello,


    I need to detect whether a DataConext has any pending changes. I need to display a warning if so when a user wants to close a dialog but changes have not been saved.


    I'd need a property of DataContext like .HasChanges or so, but it does not exist. I wrote a suggestion however, but can't wait a year for this.


    So I tried to use the GetChangeSet() method to find pending changes. But I ran into a (SERIOUS) bug that was reported in May 2008 under



    This bug was NOT address in SP1. So it seems I can't use this method either!!!


    Any idea how I can figure this out?




    Friday, September 19, 2008 1:07 PM

All replies

  • Hi 

    You can figure out pending changes with using ChangeSet class:

     ChangeSet changeSet = DataContext.GetChangeSet();

     if (changeSet.Deletes.Count != 0 || changeSet.Inserts.Count != 0 || changeSet.Updates.Count != 0)
     return false;
     return true;

    Saturday, September 20, 2008 4:38 AM


    as I wrote in my original post, calling DataContext.GetChangeSet produces an exception and probably side effect due to a bug in the DataContext class. So I can't use it.


    Here's the link to the bug report:


    I think this bug MUST be fixed soon by Microsoft!


    Any other ideas?




    Saturday, September 20, 2008 8:27 AM
  • A .HasChanges() bool property would be great.  I know that the GetChanges() method can be used, but I makes for ugly hard to read code.
    Monday, September 22, 2008 12:54 PM
  • ... an in fact GetChanges() can't be used because of the bug. Maybe you want to vote for my feature request.



    Monday, September 22, 2008 1:36 PM
  • Has there ever been a reponse on this from MS?

    I have added a HasChanges extension, and CancelChanges as well...both work well until I have a datagrid with child items.  Once I add and remove child items (ie. lines on an invoice) and attempt to call db.CancelChanges(), which in turn calls getChangeSet, I get the error...

    "An attempt was made to remove a relationship between a transact and a item. However, one of the relationship's foreign keys (item.invoiceid, item.customerid) cannot be set to null."

    I know I can drop the context and recreate it, but I would rather not.
    I saw the workaround to set my relationships to Null...but I have 108 tables and many lines of code.

    Tuesday, September 29, 2009 6:02 PM
  • Hello Jeffrey,

    yes, I received some workaround code from Mircosoft. I had a service request under the id number SRQ081010600582. I'm not sure if I'm allowed to share the code file here in public. But you might want to write to (or somebody else from developer support) and give them that number and ask for the workaround.

    Thursday, October 1, 2009 4:33 PM