Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 435
mattdwen Avatar asked Oct 05 '11 06:10

mattdwen


People also ask

How do I make Entity Framework code First?

Step 1 − First, create the console application from File → New → Project… Step 2 − Select Windows from the left pane and Console Application from the template pane. Step 3 − Enter EFCodeFirstDemo as the name and select OK. Step 4 − Right-click on your project in the solution explorer and select Manage NuGet Packages…

How do you use code first when an existing database schema?

To use code-first for an existing database, right click on your project in Visual Studio -> Add -> New Item.. Select ADO.NET Entity Data Model in the Add New Item dialog box and specify the model name (this will be a context class name) and click on Add. This will open the Entity Data Model wizard as shown below.


1 Answers

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.

like image 148
Ladislav Mrnka Avatar answered Oct 09 '22 14:10

Ladislav Mrnka