如何清除实体框架中的未决更改

编程入门 行业动态 更新时间:2024-10-10 13:24:24
本文介绍了如何清除实体框架中的未决更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我不想保存在 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.

更多推荐

如何清除实体框架中的未决更改

本文发布于:2023-11-09 07:48:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571776.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实体   框架

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!