Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Clear Pending Changes in Entity Framework

I have some table data in the DbContext that I don't want to save. I have removed the database, set it up again, but the pending changes wont go away from the DbContext.

My database table is empty after rebuilding the database, but when I call the entity as a list of objects it still contains old objects. Is there any advice on how to clear the old pending data from the DbContext using Entity Framework 6?

like image 314
Rasmus Rajje Josefsson Avatar asked Nov 05 '25 05:11

Rasmus Rajje Josefsson


2 Answers

You are holding modified objects in the DbContext, right?

If that is so, then the problem is in the fact that you are reusing the same DbContext object in the subsequent operation. You should dispose of the DbContext as soon as your current operation is over, and then create the new one for the new operation.

Generally, all your operations should have this form:

using (DbContext context = new DbContext()) // Use concrete context type
{
    // Do stuff with context
    context.SaveChanges();
} // At this point your context seizes to exist

If anything goes wrong, like having an exception, or deciding not to call SaveChanges, all intermediate changes currently held in the context will be destroyed as well.

like image 140
Zoran Horvat Avatar answered Nov 06 '25 20:11

Zoran Horvat


You have to dispose the DbContext

using (var ctx = new MyDbContext())
{
    // Do your thing...
    // Call ctx.SaveChanges();
}

using (var ctx = new MyDbContext())
{
    // Do your thing...
    // You should not find the data anymore
}
like image 34
Andrés Robinet Avatar answered Nov 06 '25 20:11

Andrés Robinet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!