views:

515

answers:

1

If I select many rows from one table with one instance of DataContext. And then do I some changes in properties in the rows, can I submit changes to database only for one of the selected rows?

+3  A: 

Yes you can.

First you need to isolate the entities you want to undo the changes. Then, you can use your DataContext class to Override those entities with the values from the Database.

MyEntity e1, e2, e3 // changed entities
...
// keep the changes only for e3
List<MyEntity> undoList = new List<MyEntity>();
undoList.Add(e1);
undoList.Add(e2);
myDataContext.Refresh(RefreshMode.OverwriteCurrentValues, undoList);

myDataContext.SubmitChanges();

EDIT:

You can track all the changed objects in the DataContext like this:

MyEntity changedEntityToSubmit; // first you need to know what is the entity you need to submit.
List<object> allChangedEntities = new List<object>(myDataContext.GetChangeSet().Updates);
allChangedEntities.Remove(changedEntityToSubmit);

myDataContext.Refresh(RefreshMode.OverwriteCurrentValues, allChangedEntities);

myDataContext.SubmitChanges();

This code is only considering the Updates. You also might need to consider the changes in Inserts and Deletes. This is up to you.

bruno conde
Thanks for answer, its exact answer to my question. But in practise is this method not so usefull, because if I don't know all entities tracked with DataContext I can not guarantee the only specified object will be submited.But you got +1 point.
TcKs
Please see the updated post (EDIT). Is this what you need?
bruno conde
Almost. But if I want preserve changes in other entities, because maybe I will need submit the changes in future, I lost the changes, right?
TcKs
But I can create clone of the entity, attach it to new DataContext, set as modified/new/deleted. Then I can remove changes from DataContext of "old" entity. The result will be same and safer, right?
TcKs
I see your point. But I don't see an easy solution for this :(
bruno conde
It's OK. I can do some helper method for this technique.Thanks a lot for your help.
TcKs