开发者

How to force EF Code First to query the database?

开发者 https://www.devze.com 2023-04-10 13:49 出处:网络
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.

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 开发者_C百科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?


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.

ObjectContext objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
ObjectSet<YourEntity> set = objectContext.CreateObjectSet<YourEntity>();
set.MergeOption = MergeOption.OverwriteChanges;
var query = from x in set where ... select x;    

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:

var query = from x context.YourEntities.AsNoTracking() where ... select x;

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消