Rasmus Rajje Josefsson
Rasmus Rajje Josefsson

Reputation: 1574

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?

Upvotes: 3

Views: 4389

Answers (2)

Zoran Horvat
Zoran Horvat

Reputation: 11301

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.

Upvotes: 4

Andrés Robinet
Andrés Robinet

Reputation: 1537

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
}

Upvotes: 3

Related Questions