title: LINQ to SQL - DuplicateKeyException during update
body: <p>The code listed below attempts to update a row in the database, but throws an exception instead:</p>
  
  <blockquote>
    <p>System.Data.Linq.DuplicateKeyException:
    Cannot add an entity with a key that
    is already in use</p>
  </blockquote>
  
  <p>Most examples I've seen query the database to obtain an instance of an entity, modify some of the instance's properties, and then update it.  Here I'm getting the object from a different source entirely (it's being parsed from an XML file) and querying to see if there's already a row for this data.  If there is, I'm setting the primary key and attempting to run an update.  What's the correct way to do this?</p>
  
  <p>Here's the trimmed down version of the code:</p>
  
  <pre><code>Customer customer = new Customer(); // Customer has a database generated
                                      // identity column called CustomerId
  
  // populate customer object
  customer.Name = "Mr. X";
  customer.Email = "x@company.com";
  // etc.
  
  // is customer already in database?
  // identify customer by email
  var results = ctx.Where(c =&gt; c.Email == customer.Email); // ctx is a DataContext
  
  if (results.Any())
  {
     Customer existing = results.Single();
  
     // set primary key to match existing one
     customer.CustomerId = existing.CustomerId;
  
     // update database
     customerTable.Attach(customer);  // customerTable is a Table&lt;Customer&gt;
     ctx.SubmitChanges();
  }
  
  // otherwise do insert
  // ...   
  </code></pre>