如何在 Entity Framework Code First 中分离对象?
DbContext
上没有 Detach(对象实体)
。
我是否能够首先分离 EF 代码上的对象?
There is no Detach(object entity)
on the DbContext
.
Do I have the ability to detach objects on EF code first?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个选项:
This is an option:
如果您想分离现有对象,请遵循@Slauma 的建议。如果您想加载对象而不跟踪更改,请使用:
如评论中所述,这不会完全分离实体。它们仍然是附加的并且延迟加载可以工作,但实体不会被跟踪。例如,如果您只想加载实体以读取数据并且不打算修改它们,则应使用此方法。
If you want to detach existing object follow @Slauma's advice. If you want to load objects without tracking changes use:
As mentioned in comment this will not completely detach entities. They are still attached and lazy loading works but entities are not tracked. This should be used for example if you want to load entity only to read data and you don't plan to modify them.
前面的两个答案都提供了很好的说明,但是,这两个答案都可能使您的实体仍然加载到 EF 的上下文和/或其更改跟踪器中。
当您更改小型数据集时,这不是问题,但当更改大型数据集时,这将成为问题。 EF 会增加内存和资源使用量,这反过来又会降低过程性能,因为它使用更多的数据/实体。
其他两种方法都是有效的,但是在这种情况下,Microsoft 建议 清理更改跟踪器而不是单独分离实体
在数据更改循环(例如更改数据块)上清除更改跟踪器可以使您免遭此麻烦。
这将从上下文中卸载/分离所有实体及其相关的changeTracker引用,因此在
context.SaveChanges()
之后小心使用。Both previous answers provide good instructions, however, both might leave you with the entities still loaded into EF's context and/or its Change Tracker.
This is not a problem when you are changing small data sets, but it will become an issue when changing large ones. EF would have increased memory and resource usage, which in turn would reduce the procedure performance as it uses more data/entities.
Both other approaches are valid but, In this case, Microsoft recommends cleaning the Change tracker instead of detaching the entities individually
Clearing the Change tracker on the data changing loop (which changes a chunk of data for instance) can save you from this trouble.
This would unload/detach all entities and its related changeTracker references from the context, so use with care after your
context.SaveChanges()
.