如何强制EF Code First查询数据库?
我有一个管理规则集合的站点和一个单独的 Windows 窗体应用程序,该应用程序根据数据库中的规则进行文件级别更改。
这两个应用程序对 EF Code First DbContext 使用相同的库,但每个应用程序都实例化自己的上下文副本。
问题是,上下文的每个正在运行的版本都不知道其他版本所做的更改。例如,如果我更改网站上的规则,表单应用程序仍具有以前的版本。
我知道我可能会采用这种错误的方式,并且应该通过 JSON/REST 从站点到表单应用程序进行某种数据访问,但出于其他原因我不想这样做。
有没有办法在上下文中“禁用缓存”并强制每个查询访问数据库?
I have a site managing a collection of rules and a separate Windows form application making file level changes based on the rules in the database.
Both of these applications use the same libraries for a EF Code First DbContext, but each application is instantiating their own copy of the context.
The problem is, each running version of the context is unaware of the changes made by the other version. E.g. If I change a rule on the site, the forms app still has the previous version.
I'm aware I'm probably going about this wrong way, and should have some kind of data access via JSON/REST from the site to the forms app, but I'd prefer not to for other reasons.
Is there a way to "disable caching" on the context and force each query to hit the DB?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,没有办法禁用缓存。您必须手动设置每个查询才能重新加载数据。该功能不适用于 DbContext API =>您必须使用 ObjectContext API。
或者更简单的场景:如果可能的话,使用更好的上下文管理,而不是在同一上下文上运行查询,我们使用新的上下文。
顺便提一句。在 winform 应用程序中公开服务并由网站使用它的想法是错误的。您将需要第三个服务应用程序(托管在 Web 服务器上或作为 Windows 服务),网站和 winform 应用程序都将通过该新应用程序访问数据库。 EF 将仅出现在新应用程序中。
编辑:
如果您的 WinForm 应用程序没有对从数据库加载的数据进行更改,您还可以使用此功能:
这将关闭实体的内部更改跟踪,并且还应该强制 EF 每次重新加载实体,但这将使保存更改变得更加困难。
No there is no way to disable caching. You must manually set each query to reaload data. That feature is not available with DbContext API => you must use ObjectContext API.
Or simpler scenario: use better context management if possible and instead of running queries on the same context us a new one.
Btw. idea of having service exposed in winform application and consumed it by web site is wrong. You would need third service application (either hosted on web server or as windows service) and both website and winform application will access database through that new application. EF would be only in the new application.
Edit:
If your WinForm application doesn't make changes to data loaded from database you can also use this:
This will turn off internal change tracking of entities and it should also force EF to reload entity each time but it will make saving changes much harder.