如何清除实体框架中的未决更改 [英] How to Clear Pending Changes in Entity Framework

查看:68
本文介绍了如何清除实体框架中的未决更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不想保存在 DbContext 中的一些表数据。我已经删除了数据库,再次进行设置,但是挂起的更改不会脱离 DbContext

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.

重建数据库后,我的数据库表为空,但是当我将该实体作为对象列表调用时,它仍然包含旧对象。关于如何使用Entity Framework 6从 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?

推荐答案

您要在 DbContext 中保存修改过的对象,对吧?

You are holding modified objects in the DbContext, right?

如果是这样,那么问题就在于您在随后的代码中重用了相同的 DbContext 对象操作。您应在当前操作结束后立即处置 DbContext ,然后为新操作创建新的操作。

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

如果出现任何问题,例如发生异常,或者决定不调用 SaveChanges ,上下文中当前持有的所有中间更改也将被销毁。

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.

这篇关于如何清除实体框架中的未决更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆