Search code examples
c#linqdatacontext

For DataContext, GetChangeSet stops working after SubmitChanges


In our project, we have multiple System.Data.Linq.DataContext objects for the different Windows forms.

When databound controls on the form are changed (like the Name), we enable or disable the Save Button by checking the GetChangeSet method.

private void ContentChanged(object sender, EventArgs e)
{
    var changes = GetChangeSet();
    int numChanges = changes.Deletes.Count + changes.Inserts.Count + changes.Updates.Count;
    btnSubmit.Enabled = (numChanges > 0);
}

When the Save Button is clicked, we call SubmitChanges on the Linq DataContext followed by a call to a ClearCache extension on the DataContext:

bool IFormPanelAccessor.CommitChanges<T>(T record)
{
    _dc.SubmitChanges();
    _dc.ClearCache();
}

ClearCache is defined in a static extensions class as follows:

public static void ClearCache(this DataContext dc)
{
    dc.GetType().InvokeMember("ClearCache", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, dc, null);
}

After saving, subsequent changes in the DataContext are no longer detected with GetChangeSet.

There is a trigger on the database that is called after an Insert or Update. Would this somehow break the DataContext's ability to detect changes?

How do I get GetChangeSet to detect changes on databound controls after a call to SubmitChanges?


Solution

  • Similar to jdweng's comment in the original question, I found a way to reload the data.

    private void CommitChanges()
    {
        // mCustomer is a record from the CustomerRecords Linq DataTable
        var rowId = mCustomer.RowId;
        _dc.SubmitChanges();
        _dc.ClearCache();
        // After ClearCache, it seems I need to physically pull the data again:
        mCustomer = _dc.CustomerRecords.FirstOrDefault(c => c.RowId == rowId);
        // Use the new record to update the controls on the form
        LoadData(mCustomer);
    }
    

    My guess is that ClearCache was causing the current record to lose its connection to the data.

    Seems simple in hindsight, but I just never realized that.