title: Entity framework: adding new objects results in duplicates
body: <p>I'm developing a 3-tier WinForms application. But when I try to add a new object to the database, some objects get duplicated.</p>
  
  <p>Classes:</p>
  
  <pre><code>class Customer 
  {
      public int Id { get; set; }
      public int CustomerName { get; set; }
  
      public virtual IList&lt;CustomerAccount&gt; CustomerAccount { get; set; }
  }
  
  class CustomerAccount
  {
      public int Id { get; set; }
      public int CustomerId { get; set; }
      public int AccountId { get; set; }
  
      public virtual Customer Customer { get; set; }
      public virtual Account Account { get; set; }
  }
  
  class Account
  {
      public int Id { get; set; }
      public int AccountName { get; set; }
  }
  </code></pre>
  
  <p>This is the code I use to add the Customer object to the database:</p>
  
  <pre><code> DataContext.CustomerSet.Add(customer);
   DataContext.SaveChanges();
  </code></pre>
  
  <p>The accounts that are added to the customer are existing accounts. And these are the rows that are duplicated in the database. So for example:</p>
  
  <pre><code>Customer c;
  c.CustomerName = "Kevin";
  
  c.CustomerAccount.Add(new CustomerAccount() {
      AccountId = existingAccountId,
      Account = existingAccount
  }
  
  AddCustomer(c);
  </code></pre>
  
  <p>In this example, existingAccount gets duplicated.</p>
  
  <p>I know it's something with the DataContext.Attach() method. But that doesn't work when there is more than one CustomerAccount relation added. (An object with the same key already exists in the ObjectStateManager.)</p>
  
  <p>Thanx in advance.</p>