title: LINQ to SQL: To Attach or Not To Attach
body: <p>So I'm have a <em>really</em> hard time figuring out when I should be attaching to an object and when I shouldn't be attaching to an object. First thing's first, here is a small diagram of my (very simplified) object model.</p>
  
  <p><img src="https://i.imgur.com/2ROFI.png" alt="Schema"></p>
  
  <p>In my DAL I create a new DataContext every time I do a data-related operation. Say, for instance, I want to save a new user. In my business layer I create a new user.</p>
  
  <pre><code>var user = new User();
  user.FirstName = "Bob";
  user.LastName = "Smith";
  user.Username = "bob.smith";
  user.Password = StringUtilities.EncodePassword("MyPassword123");
  user.Organization = someOrganization; // Assume that someOrganization was loaded and it's data context has been garbage collected.
  </code></pre>
  
  <p>Now I want to go <em>save</em> this user.</p>
  
  <pre><code>var userRepository = new RepositoryFactory.GetRepository&lt;UserRepository&gt;();
  userRepository.Save(user);
  </code></pre>
  
  <p>Neato! Here is my save logic:</p>
  
  <pre><code>public void Save(User user)
  {
   if (!DataContext.Users.Contains(user))
   {
    user.Id = Guid.NewGuid();
    user.CreatedDate = DateTime.Now;
    user.Disabled = false;
  
    //DataContext.Organizations.Attach(user.Organization);
    DataContext.Users.InsertOnSubmit(user);
   }
   else 
   {
    DataContext.Users.Attach(user);
   }
  
   DataContext.SubmitChanges();
  
   // Finished here as well.
   user.Detach();
  }
  </code></pre>
  
  <p>So, here we are. You'll notice that I comment out the bit where the DataContext attachs to the organization. If I attach to the organization I get the following exception: </p>
  
  <blockquote>
    <p><strong>NotSupportedException:</strong> <em>An attempt has been made to Attach or Add an
    entity that is not new, perhaps having
    been loaded from another DataContext. 
    This is not supported.</em></p>
  </blockquote>
  
  <p>Hmm, that doesn't work. Let me try it <em>without</em> attaching (i.e. comment out that line about attaching to the organization).</p>
  
  <blockquote>
    <p><strong>DuplicateKeyException:</strong> <em>Cannot add an entity with a key that is already
    in use.</em></p>
  </blockquote>
  
  <p>WHAAAAT? I can only assume this is trying to insert a new organization which is obviously false.</p>
  
  <p>So, what's the deal guys? What should I do? What is the proper approach? It seems like L2S makes this quite a bit harder than it should be...</p>
  
  <p><strong>EDIT:</strong> I just noticed that if I try to look at the pending change set (dataContext.GetChangeSet()) I get the same NotSupportedException I described earlier!! What the hell, L2S?!</p>