开发者

how to discard changes made to all linq tables?

开发者 https://www.devze.com 2022-12-17 11:56 出处:网络
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?

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 t开发者_如何学JAVArans

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.

The question

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:

  1. refetching all data
  2. recreating connection to DB (because it leads to (1))


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消