views:

325

answers:

2

I have this problem where after a field (say Field3 in table MyTable) is updated on the database, MyTable.Field3 (in C#) is still returning the old value.

I suspect there is some caching...?

How do I force it to:
Read the value from the database?
OR
Update the value in the MyTable class?

Or is there anything I miss? I am new to LINQ

Thank you in advance.

+5  A: 

You're misunderstanding the model. Linq to SQL doesn't pass through to the database each time you ask for a member. When you fetch an object from the database, it gets stored in memory as a Linq to SQL object, and there it stands. You don't get an up-to-date version of the object until you query the database again.

Dave Markle
I see, that's what I thought, thanks Dave. So how do I make it sync the value in the memory to match the one in the database?
You would request the object again from the DataContext.
Robert Harvey
How do you do that Robert?
Alright I've actually been doing this wrong I have a lot of instances of DataContext everywhere. I'll fix that first.
A: 
DataContext.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, entity);

If you want to refresh your entire entity set, the easiest way is probably to just create a new DataContext and requery for everything.

Jake
It throws this exception:An object specified for refresh is not recognized.Apparently the record is changed using Context.SubmitChanges();I can tell if a record is being updated, how do I refresh the value just for that record just after it is updated?
Is there any sample code anywhere? I don't even know the terms I need to google, what should I search? Thank you
When you call SubmitChanges(), your object should will refresh itself. If it does not, check the UpdateMode property on the fields in your Linq to SQL data model to make sure that it's set to "auto update".
Dave Markle
Thanks Dave, it may be because I was using different instances of DataContext.