I would like to discard all changes made to linq tables (this means -- I use linq, and data are changed on client side, the data on server are intact). How to do this?
EDIT: problem partially solved
http://graemehill.ca/discard-changes-in-linq-to-sql-datacontext/
It works as long as you don't use transaction. When you do and you use mixed "mode" for a record, there is a problem:
begin trans
insert a record
update inserted record
commit trans
When you update record as above Linq counts it as updated record, and in case of exception you have two actions -- transaction is rolled back and data on Linq side are discarded. On discard changes Linq tries to fetch it from the database (discard for update means refetching data for a record), but since all changes were rolled back, there is no records for update.
How to improve DiscardChanges method in a smart general way to work with transactions. Or how to change the workflow of transactions/discard-submitchanges to make all those work together?
Those are not smart solutions:
To add to what Johannes said, I think the confusion here stems from thinking of the DataContext
as something similar to a DataSet
. It isn't.
A "table" in a DataContext
is like a hint on how to retrieve a specific type of data entity from the database. Unlike a DataSet
, the DataContext
does not actually "contain" data, it simply tracks the discrete entities you've pulled out of it. If the DataContext
disappears (is disposed), the entities are still valid, they are simply detached. This is different from a DataSet
where the individual DataTables
and DataRows
are essentially bound to their containers and cannot outlive them.
In order to use the Refresh
method of a DataContext
, you need to use it on an actual entity or collection of entities. You can't "Refresh" a Table<T>
because it's not actually a physical table, it's just a kind of reference.
Changes to entities connected to a DataContext
are only persisted when you call the SubmitChanges
method. If you dispose of the DataContext
, there is absolutely no way that the changes can persist unless you manually reattach the detached entities to a new DataContext
.
Simply discard the current DataContext without calling SubmitChanges() and get a new one.
Example:
DataContext myOldDc = new DataContext();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With