LINQ old data being returned
I didn't get any where on Microsoft's forum. What worked for one user didn't work for me so I must be doing something wrong.
I need the data returned to match what's in the database, but 6 seconds later it's coming back as the previous data that was just updated. I'm creating the context within the method and I'm using StoreWins, but maybe I'm using it incorrectly.
Here's an example method.
public bool MyExampleMethod(long id, long newId, long oldId)
{
using (var context = new myEntity())
{
my_table data = (from d in context.my_table
where d.id == id
select d).FirstOrDefault();
context.Refresh(System.Data.Objects.RefreshMode.StoreWins, data);
if (data.dataId != oldId) { return false; }
data.dataId = newId;
context.SaveChanges();
return true;
}
}
I have some logging in there as well with timestamps cuz I keep track of the oldId. I've seen (more than once) 6 seconds later the method called again using the wrong (old oldId) and the row is returned with the old oldId instead of the previously set newId. This is impossible because dataId was changed to the newId and saved. The newId never, ev开发者_运维知识库er matches the oldId and I've verified that this isn't happening. The problem is happening randomly. 99% of the time it's fine, but when it returns the old data it creates a lot of bad data that I have to manually fix.
Should I be doing something after context.SaveChanges()? or am I using StoreWins incorrectly?
More info:
id: Primary key/identity column.
newId: This is the user Id of the person updating the row
oldId: This is the user id of the person who last updated the row
I need to make sure the row wasn't changed by someone else before updating it. Originally I had oldId in the LINQ code but changed it while trying to figure out why old data was coming back.
The point is if someone else changes the row and it's already been changed by someone else I need to notify the user.
Today I saw 16 seconds later old data was returned by the LINQ code (I have timestamps). I'm beginning to think the problem is that the changes aren't actually being saved sometimes or it's some kind of caching issue.
Update: I think I might know why.. running some tests.
I have never seen it done in the manner you are doing it. Usually you attempt a save in a try block. if it fails because of a concurrency exception then you do the context.refresh in your catch block;
try
{
int num = context.SaveChanges();
}
catch (OptimisticConcurrencyException)
{
context.Refresh(RefreshMode.ClientWins, data);
context.SaveChanges();
}
This line confuses me:
where d.id == id
Should it be
where d.dataId == id
If not please explain what the difference between
id
, newId
, oldId
, data.id
, and data.dataId
精彩评论