如何从数据库刷新ObjectContext缓存?

发布于 2024-08-23 01:39:48 字数 248 浏览 9 评论 0原文

我们正在从数据库加载数据:

var somethings = Context.SomethingSet.ToList();

然后有人在上下文之外删除或添加行。 Out context 仍然缓存已删除的对象,因为它不知道它们已被删除。即使我调用 Context.SomethingSet.ToList(),我们的上下文仍然包含已删除的对象,并且导航属性不正确。

从数据库刷新整个集合的最佳方法是什么?

We are loading data from db:

var somethings = Context.SomethingSet.ToList();

Then someone deletes or adds rows outside of context. Out context still has caches deleted object, because it doesn't know they were deleted. Even if I call Context.SomethingSet.ToList(), our context still contains deleted objects and navigation properties are not correct.

What is the best method to refresh whole set from database?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

初见终念 2024-08-30 01:39:48

您正在寻找 Refresh 方法:

Context.Refresh(RefreshMode.StoreWins, somethings);

The Refresh method is what you are looking for:

Context.Refresh(RefreshMode.StoreWins, somethings);
绿萝 2024-08-30 01:39:48

EF 数据上下文是工作单元模式的实现。因此,它的设计目的不是要保留在正在完成的工作单元之外。一旦您的工作完成,您的数据上下文就会被丢弃。

这是 EF v1、EF v4 和 LINQ to SQL 的基本设计决策。除非您有非常具体的数据使用模式和大量内存,否则您应该避免将数据上下文保留的时间超过完成工作单元所需的时间。

http://sdesmedt.wordpress.com/2009/02/ 18/unit-of-work-pattern/

http://takacsot.freeblog .hu/Files/martinfowler/unitOfWork.html

The EF data context is an implementation of the Unit of Work pattern. As such, it is NOT designed to be keept around beyond the unit of work that is being done. Once your work is done, the expectation is that your data context is discarded.

This is a fundamental design decision for both EF v1, EF v4, and LINQ to SQL. Unless you have very specific data usage patterns and copious volumes of memory, you should avoid keeping your data contexts around longer than absolutely needed to complete your unit of work.

http://sdesmedt.wordpress.com/2009/02/18/unit-of-work-pattern/

http://takacsot.freeblog.hu/Files/martinfowler/unitOfWork.html

时光瘦了 2024-08-30 01:39:48

对于虚拟属性重新加载没有帮助。它需要分离并再次加载

public T Reload<T>(T entity) where T : class, IEntityId
{
    ((IObjectContextAdapter)_dbContext).ObjectContext.Detach(entity);
    return _dbContext.Set<T>().FirstOrDefault(x => x.Id == entity.Id);
}

For virtual properties Reload doesn't help. It needs to detach and load again

public T Reload<T>(T entity) where T : class, IEntityId
{
    ((IObjectContextAdapter)_dbContext).ObjectContext.Detach(entity);
    return _dbContext.Set<T>().FirstOrDefault(x => x.Id == entity.Id);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文