Search code examples
c#linqlinq-to-sqldatacontext

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?


Solution

  • 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);
    }