Link to home
Start Free TrialLog in
Avatar of Dan Schimo
Dan SchimoFlag for United States of America

asked on

Entity Framework - Can't Delete a row from a grid. An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

Hello Experts,

I got a page with a gridview.  want to delete the row, so I click the delete button on the row.

I am seeing this error and banging my head.
An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
                     TableCell cell = GridView1.Rows[e.RowIndex].Cells[1];

                     _process.DeleteAttachmentByID(Convert.ToInt32(cell.Text));
                    
                 
        }

----**************************************---------


 public void DeleteAttachmentByID(int AttachmentID)
        {

            var reqAttach = GetRequestAttachmentByID(4);

            RequestAttachmentRepository rep = new RequestAttachmentRepository();            

            rep.DeleteEntity(reqAttach);
        }


_*************************************************--

 public void DeleteEntity(T entity)
        {
            Context.Entry<T>(entity).State = EntityState.Deleted;
            Context.SaveChanges();
        }

        

Open in new window



-- Dan
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

The EntityChangeTracker Provides access to features of the context that deal with change tracking of entities. So the error sounds like you may have two DbContext or are trying to attach something to the EntityChangeTracker which already is tracking the entity you are trying to add. Can't tell from the code posted so look for how you are actually deleting the entity.
Avatar of Dan Schimo

ASKER

I have the grid view populating from the context, and a delete button on the grid is deleting it.

1 DBcontext has populated the grid
and
2 another DBContext is being used to delete member of the from the entity.

is this what you are trying to say sir ?
SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Redesigned Code