Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detach a LINQ-to-SQL data object from the DataContext's tracking mechanism?

After asking this question, where I was informed of how the Table<T>.Attach() method works, I have another question.

How do you detach a LINQ-to-SQL data object from the DataContext's state tracking mechanism? Basically, I want to pull a record and change the data on the record. But, when I call SubmitChanges() on the same DataContext instance, I do not want the record to be updated unless I have explicitly called Attach(). How is this accomplished?

like image 964
smartcaveman Avatar asked Mar 09 '11 10:03

smartcaveman


3 Answers

Unfortunately, you cannot explicitly detach entities from previous DataContext, without serializing and deserializing the entities.

What you can do for your purpose is to create a copy of the object you pulled out of the DB and work with the copy. In this case your original object is untouched. When the time comes to update the DB, you can simply attach the copy to your DataContext.

like image 67
Andrei Avatar answered Nov 02 '22 04:11

Andrei


From this site explaining how to detach a linq object add this method to the object you want to detach:

public void Detach()
{
    GetType().GetMethod("Initialize", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(this, null);
}
like image 36
user281806 Avatar answered Nov 02 '22 02:11

user281806


I strongly recommend that if you're going to use LINQ to SQL, you should change your design to accommodate LINQ to SQL's behavior of submitting changes on all attached modified entities. In my experience, attempting to work around this feature will only lead to pain.

like image 9
shaunmartin Avatar answered Nov 02 '22 03:11

shaunmartin