Reputation: 87
Why is it that the two tests at the end of this code return different results? They both query the same data context but one returns ‘111’ the other ‘222’?
//Make two contexts
myAppContext context1 = new myAppContext();
myAppContext context2 = new myAppContext();
// Select and Modify Campaign id 1 using context 1
var SingleCam = context1.Campaigns.Where(c => c.CamId == 1).Single();
SingleCam.CamApplications = 111;
context1.Entry(SingleCam).State = System.Data.Entity.EntityState.Modified;
context1.SaveChanges();
// Select and Modify Campaign id 1 again using context 2
var SingleCam2 = context2.Campaigns.Where(c => c.CamId == 1).Single();
SingleCam2.CamApplications = 222;
context2.Entry(SingleCam2).State = System.Data.Entity.EntityState.Modified;
context2.SaveChanges();
// Access the Campaign through the same Context (1) and get two differnt results
var mycams = context1.Campaigns.ToList();
System.Diagnostics.Debug.WriteLine("Test 1 = " + mycams.Where(o => o.CamId == 1).Select(o => o.CamApplications).FirstOrDefault()); //returns 111
System.Diagnostics.Debug.WriteLine("Test 2 = " + context1.Campaigns.Where(o => o.CamId == 1).Select(o => o.CamApplications).FirstOrDefault()); //returns 222
Upvotes: 2
Views: 274
Reputation: 1539
The behaviour you are seeing is perfectly normal, even if it seems odd. While the value in the database has indeed been updated to 222, you still have some stale data in your objects.
When you call
context1.SaveChanges();
the changes get persisted to the database (111).
You then call
context2.SaveChanges();
and these changes get persisted to the database (222).
var mycams
is based on an existing object (context1.Campaigns
), which still has a value of 111. A query is executed but the Entity Framework uses its cached values of the entities (thanks to @GertArnold for making this point).
context1.Campaigns.Where(...)
will retrieve data from the DB, rather than from the cache, which is why you see 222.
Upvotes: 2