如何确保使用实体框架的存储库调用不被缓存?
当我之前对数据进行存储库调用时,我从未遇到过对数据库的任何更改没有反映的问题。但现在这种情况似乎正在发生。
以前,此类存储库调用始终处于使用存储库模式的上下文中,其中存储库 i/fs 被注入到服务/控制器构造函数中。
我有一个作为控制台应用程序编写的电子邮件任务,其中包含 while() 循环,该循环询问数据库中的电子邮件帐户,然后从相应的服务器下载电子邮件。问题是,每次我调用 _emailSettingsRepo.GetAll() 方法时,所有设置都是旧的,并且不会显示对数据库的任何更改,即使我可以在 Management Studio 中看到更改。我猜这是因为我在循环内使用相同的存储库来使用相同的数据库上下文,因此调用 GetAll() 方法没有任何区别。
这是否意味着缓存以前从未成为存储库的问题,因此每次新请求进入控制器时都会重新创建数据库上下文?我该如何解决这个问题?
I've never had a problem with any changes to the db not being reflected when I make a repository call on the data before. But this now seems to be happening.
Before, such repository calls have always been in the context of using the repository pattern where the repository i/fs are injected into the service/controller constructors.
I have an email task written as a console app, containing a while() loop, which interrogates the database for email accounts and then downloads emails from the respective servers. The problem is, every time I make a call to the _emailSettingsRepo.GetAll() method, all of the settings are old and don't show any changes to the database even though I can see the change in management studio. I'm guessing this is because I'm using the same db context by using the same repo inside the loop, so making the GetAll() method call doesn't make any difference.
Does this mean that the caching has never been a problem before as the repo and therefore db context is re-created each time a new request comes into the controller? How do I get round this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在需要时创建一个上下文并在之后处理它,类似于:
将此控制台应用程序与有关上下文管理的 Web 应用程序进行比较,认为每次循环运行都是一个 Web 请求。如果您在 Web 应用程序中使用 IOC 容器(例如 Ninject),则该容器很可能会创建上下文并为您处理它。但它始终是一对
context = new MyContext()
和context.Dispose()
以及其间的请求处理。因此,基本上与上面示例中的using
块相同。您现在只需在控制台应用程序中明确执行即可。Create a context when you need it and dispose it afterwards, something like:
Comparing this console app with a web app regarding context management, think that every run through the loop is a web request. If you are using an IOC container in your web app (for example Ninject) it is well possible that the container creates the context and disposes it for you. But it is always a pair of
context = new MyContext()
andcontext.Dispose()
and the request processing in between. So, basically the same like theusing
block in the example above. You just have to do it explicitely now in your console app.