LINQ to SQL does not update when data has changed

2020-02-06 18:30发布

问题:

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.

回答1:

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.



回答2:

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.