Why am I getting "Object is in a deleted or deleted state" when deleting an unchanged row?

I am using EntityFramework 4 to manage my data in a simple grid. We just need to keep track of the checkbox in the table. It was intended to be a quick fix for I / O from a small table, not a large project.

I have the following definition in my form

private MyDBEntites _context = new MyDBEntities(...);
private BindingSource myBindingSource = new BindingSource(...);
public DataGridView myGrid = new DataGridView();

      

In my constructor, I fill in the grid

    int customerID = 1234;

    myGrid.DataSource = myBindingSource;

    myBindingSource.DataSource = (from cc In _context.myRecords
                                  where cc.CustomerID = customerID
                                  select cc).AsEnumerable();

      

My intention is to then modify the table as needed. When I am done making changes, I click the button that calls SaveForm ()

public void SaveForm()
{
    _context.SaveChanges();
}

      

For adding and modifying lines, this works very well. However, when I remove the line and then call SaveChanges, above, my application crashes with "Object is in detached or deleted state". This is even true when I did nothing but delete the line.

Why can't I delete a line this way? Does anyone know what might be "changed" before deleting? If so, do you know how I can get around this?

UPDATE

I still don't know WHY it fails, but I have a workaround. I was trying to enqueue deletes and manage all my changes with one call to SaveChanges (). There was no need for business for this. Just personal preference. Instead, I put SaveChanges at the end of Remove and it works great.

private void myGrid_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
    if (e.Row == null) 
    {
        return;
    }

    if ((MessageBox.Show("Are you certain that you want to delete this entry?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)) 
    {
        myRecord req = (myRecord)e.Row.DataBoundItem;

        myBindingSource.Remove(req);
        _context.myRecords.DeleteObject(req);

        _context.SaveChanges();
    }
}

      

+3


source to share





All Articles