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?
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.
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);
}
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.
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