Search code examples
c#.netstrongly-typed-dataset

DeletedRowInaccessibleException while doing for each


I understand what the exception means, what I do not understand is why are the rows that are marked for deletion being picked up even when I mention a predicate dataRow.RowState != DataRowState.Deleted in my 'where' clause?

    //DataSet is a strongly typed dataset
    DataSet.TableB_row rowToDelete = dataSet.TableB.where(x=>x.ID==ID).First();
    rowToDelete.Delete(); 
    //don't want to use Remove(), might have to do RejectChanges depending on logic
    //I do not want to call AcceptChanges just yet.
    var results = (from rowA in dataSet.TableA
                   join rowB in dataSet.TableB
                        on rowA.ID equals rowB.ID
                   join rowC in dataSet.TableC
                        on rowB.ID equals rowC.ID
                    where rowB.RowState != DataRowState.Deleted
    //added RowState check for other tables hoping that might fix, but didn't
                        && rowA.RowState != DataRowState.Deleted
                        && rowC.RowState != DataRowState.Deleted
                        && rowA.ID == someID
                        select new { rowB.ColA, rowC.ColA });

    foreach (var result in results)
    {
       //deletedRowInaccessibleException thrown
       //some logic, not modifying the collection. Doesn't even get this far.
    }

Certainly I am doing something wrong, but can't figure out. Similar post on SO, mostly suggest adding RowState check, which I already have.


Solution

  • Without accepting the changes, the join seems to try to evaluate the ID of the deleted row before filtering it out with where clause. To work around that, you could first create a "bRows" query and use that in the join, rather than using TableB directly. Something like this.

    var bRows = dataset.TableB.Where(r => r.RowState != DataRowState.Delete);
    var results = (from rowA in dataset.TableA
                   join rowB in bRows
                        on rowA.ID equals rowB.ID
                   join rowC in dataset.TableC
                        on rowB.ID equals rowC.ID
                   select new { rowB.ColA, rowC.ColA });