What is the correct usage of DataContext.Refresh()

2019-06-16 19:46发布

问题:

I have a LinqToSql object in memory, whose field values on the database are expected to change during the lifetime of the object. So periodically I need to check if everything is still in sync. I was expecting to be able to do this like so:

myDataContext.Refresh(RefreshMode.KeepCurrentValues, myObj);

but unfortunately this seems to have no effect; the values on myObj remain the same even when the DB values have changed. MSDN documentation on this method is pretty scant. Can anyone tell me what I am missing here?

回答1:

If you want your refreshed object's current values to match what's currently in the database you'll need to use RefreshMode.OverwriteCurrentValues mode instead.



回答2:

If you want to "refresh" your entity with the up-to-date values, then the appropriate mode would be RefreshMode.KeepChanges or RefreshMode.OverwriteCurrentValues.

KeepChanges will leave any locally changed value as is. OverwriteCurrentValues will fetch all values from the database.

Beware of ChangeConflictExceptions.