Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
658 views
in Technique[技术] by (71.8m points)

entity framework 4 - How to force EF Code First to query 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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...