Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Read after SaveChanges Gets Old Values

I am working with Entity Framework 5.0 and a SQLite database. I have a scenario where I make modifications to a database record and then I use a new instance of the entity object for the same table to read that same record, but I get the old values. While debugging, if I go to my database tool and look at the record, the changes are there, but EF isn't picking them up. It will pick them up eventually later on, but I can't determine when that is.

Here are the code snippets. First I perform the update using SaveChanges():

tblTest efTestTbl = context.tblTests.Find(recID);
context.tblTests.Attach(efTestTbl);
efTestTbl.Value1 = "newValue";  // This changed it from "oldValue" :-)
int changedRecs = context.SaveChanges();

This code above seems to always work and saves the changes to the database. changedRecs ends up being equal to 1. I can stop at a break after this point in the code and see the value in the database, using my database tool, and the column will equal "newValue".

Now, if I perform the following read, directly after the previous update with a different table object, but same instance of the context object:

tblTest efTestTbl = context.tblTests.Find(recID);

The value in efTestTbl.Value1 will equal "oldValue". I've seen some comments about EF not caching anything, but I can't believe that is true. In another forum, I saw a conversation talking about the MergeOption for an ObjectQuery and the caching was called "identity resolution". This was informative, but didn't help me as I'm not using queries and "ExecuteNonQuery()" methods.

My scenario needs me to write out a change and then read and log the change from the database as a verification step.

Any help you can give me to find a way to flush the cache would be most appreciated.

like image 527
user2975847 Avatar asked Jun 13 '26 17:06

user2975847


1 Answers

Depending on what's happening within your context the object you're trying to load may already be present in the other context.

This is what I've done to fix this before;

public static class ZarettoContextExtensionClass
{
    public static tblTest Reload(this tblTest item, DbContext c)
    {
        c.Configuration.AutoDetectChangesEnabled = false;
        c.Entry(item).Reload();
        c.Configuration.AutoDetectChangesEnabled = true;
        return item;
    }
}

then obviously you'd do:

efTestTbl.Reload(context)
like image 79
Richard Harrison Avatar answered Jun 15 '26 06:06

Richard Harrison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!