title: Entity Framework Updating Many-To-Many Relationships - POCO
body: <p>I have following Many-To-Many relationship between two entities <strong>RelayConfig</strong> and <strong>StandardContact</strong></p>
  
  <p><strong>Entities:</strong></p>
  
  <pre><code>public class RelayConfig : EntityBase, IDataErrorInfo {
      ...
      //Associations
      public virtual ICollection&lt;StandardContact&gt; StandardContacts { get; set; }
  }
  
  
  public class StandardContact :EntityBase, IDataErrorInfo {
      ...
      //Associations
      public virtual ICollection&lt;RelayConfig&gt; RelayConfigs { get; set; }
  }
  </code></pre>
  
  <p>Now I am trying to update RelayConfig and its relations with the StandardContact. Here is the code that updates RelayConfig.</p>
  
  <pre><code>public class RelayConfigRepository : GenericRepository&lt;RelayConfig&gt; {
      ....
  
      public void Update(RelayConfig relayConfig, List&lt;StandardContact&gt; addedContacts, List&lt;StandardContact&gt; deletedContacts) {
          context.RelayConfigs.Add(relayConfig);
          if (relayConfig.Id &gt; 0) {
              context.Entry(relayConfig).State = EntityState.Modified;
          }
  
          addedContacts.ForEach(ad =&gt; relayConfig.StandardContacts.Add(ad));
  
          foreach (StandardContact standardContact in relayConfig.StandardContacts) {
              if (standardContact.Id &gt; 0) {
                  context.Entry(standardContact).State = EntityState.Modified;
              }
          }
  
          relayConfig.StandardContacts.ToList().ForEach(s =&gt; {
              if (deletedContacts.Any(ds =&gt; ds.Id == s.Id)) {
                  context.Entry(s).State = EntityState.Deleted;
              }
          });
      }
      ...
  }
  </code></pre>
  
  <p>When I run the update, I am getting exception, whose inner exception is given below.</p>
  
  <pre><code>InnerException: System.Data.SqlClient.SqlException
          Message=Violation of PRIMARY KEY constraint 'PK__Standard__EE33D91D1A14E395'. Cannot insert duplicate key in object 'dbo.StandardContactRelayConfigs'.
  </code></pre>
  
  <p>dbo.StandardContactRelayConfigs is the linking table that links RelayConfig and StandardContact. As you can see, the Update code changes all the entities to modified state if Id > 0 (except deleted records that are set in the end of the Update method). </p>
  
  <p>I really cannot understand why entity framework is trying to insert row in the linked table and failing with the above exception. I already change the EntityState of existing RelayConfig.StandardContacts entities to Modified. </p>
  
  <p>In short why do I get the exception pasted above.</p>
  
  <p>regards,
  Nirvan.</p>
  
  <p><strong>Edit:</strong>
  The parameters to Update method above (addedContacts and deletedContacts) are already existing entities with Id > 0.</p>
  
  <p><strong>Edit2:</strong>
  As per your suggestions I removed the code for inserting fresh (not existing in database) records from the update method. So now my update method only adds existing StandardContact records to RelayConfig collection. But I still cannot get the code to work properly. First here is the code that I am using</p>
  
  <pre><code>    public void Update(RelayConfig relayConfig, List&lt;StandardContact&gt; addedContacts, List&lt;StandardContact&gt; deletedContacts) {
          context.RelayConfigs.Add(relayConfig);
  
          if (relayConfig.Id &gt; 0) {
              context.Entry(relayConfig).State = EntityState.Modified;
          }
  
  
          addedContacts.ForEach(contact =&gt; {
              context.StandardContacts.Attach(contact);
              relayConfig.StandardContacts.Add(contact);
              objectContext.ObjectStateManager.
                  ChangeRelationshipState(relayConfig, contact, rs =&gt; rs.StandardContacts, EntityState.Added);
          });
      }
  </code></pre>
  
  <p>For now I am just concentrating on added records. The above code works well when the StandardContact (contact variable) does not have any relationships with any other existing RelayConfig objects. In that case, a new entry is created in the junction table for each contact added to the RelayConfig.StandardContacts collection. But things get ugly (unpredictable behaviour) when the StandardContact (contact variable) is already in relationship with other RelayConfig objects. In that case, when the StandardContact is added to RelayConfig.StandardContacts Collection, the StandardContact also gets added in the database thus creating duplicate entry. Not only that, a new RelayConfig object is also created (I don't know from where) and inserted to the RelayConfigs table. I am really not able to comprehend the way entity framework works with Many-To-Many relationships. </p>
  
  <p>@Ladislav, if you have some sample code that works on Many-To-Many relationship updates (for detached entities) then can I request you to please show me the same.</p>
  
  <p>regards,
  Nirvan</p>
  
  <p><strong>Edit3 (Solution):</strong></p>
  
  <p>Eventually I ended up using a completely different approach. Here is the code for the Update</p>
  
  <pre><code>    public void Update(RelayConfig relayConfig, List&lt;StandardContact&gt; exposedContacts) {
  
          context.Entry(relayConfig).State = EntityState.Modified;
  
          relayConfig.StandardContacts.Clear();
          exposedContacts.ForEach(exposedContact =&gt; {
              StandardContact exposedContactEntity = null;
              exposedContactEntity = context.StandardContacts.SingleOrDefault(sc =&gt; sc.Id == exposedContact.Id);
              if (exposedContactEntity != null) {
                  relayConfig.StandardContacts.Add(exposedContactEntity);
              }
          });
      }
  </code></pre>
  
  <p>regards,
  Nirvan.</p>