Search code examples
c#entity-frameworkobjectdelete-row

Cannot delete a data row using Entity Framework model


I'm trying to delete an item in my application. This is how I try to do it in my button click event. First I check if the item exists in the database and then I proceed with deleting.

But when I try to delete, I get this error:

An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

My code:

private void btnRemove_Click(object sender, EventArgs e)
{
    if (MessageBox.Show("Do you want to proceed with deleting?", "System Alert", MessageBoxButtons.YesNo) == DialogResult.Yes)
    {
        int jid = 0;
        int ProdLine = 0;
        int seritid = 0;

        if (dgvServices.SelectedRows.Count != 0)
        {
            DataGridViewRow row = this.dgvServices.SelectedRows[0];
            jid = Convert.ToInt32(row.Cells["JID"].Value.ToString());
            ProdLine = Convert.ToInt32(row.Cells["ProdLine"].Value.ToString());
            seritid = Convert.ToInt32(row.Cells["ServiceItem"].Value.ToString());
        }

        using (DataControllers.RIT_Allocation_Entities RAE = new DataControllers.RIT_Allocation_Entities())
        {
            jsmodel2 = RAE.Job_Service.Where(a => a.JID == jid && a.ProdLine == ProdLine && a.ServiceItem == seritid).OrderByDescending(x => x.ServiceItem) 
                                      .Take(1).FirstOrDefault();

            if (jsmodel2 == null)
            {
                // No service item exists for this
                // Nothing to delete
                MessageBox.Show("The item doesn't exist ","Alert");
                return;
            }
            else
            {
                // Delete
                using (DataControllers.RIT_Allocation_Entities RAEE = new DataControllers.RIT_Allocation_Entities())
                {
                    var entry = RAEE.Entry(jsmodel2);

                    if (entry.State == EntityState.Detached)
                    {
                        RAEE.Job_Service.Attach(jsmodel2);
                        RAEE.Job_Service.Remove(jsmodel2);
                        RAEE.SaveChanges();
                        populateServiceDetailsGrid();
                    }
                }
            }
        }                
    }          
}

How can I overcome this?


Solution

  • Your entity is already tracked by RAE (thus the error), so you don't need a second DbContest. Simply replace:

    // Delete
    using (DataControllers.RIT_Allocation_Entities RAEE = new DataControllers.RIT_Allocation_Entities())
    {
      var entry = RAEE.Entry(jsmodel2);
    
      if (entry.State == EntityState.Detached)
      {
        RAEE.Job_Service.Attach(jsmodel2);
        RAEE.Job_Service.Remove(jsmodel2);
        RAEE.SaveChanges();
        populateServiceDetailsGrid();
      }
    }
    

    with

     RAE.Job_Service.Remove(jsmodel2);
     RAE.SaveChanges();
     populateServiceDetailsGrid();