title: EF6 Many-to-Many Relation Duplicate Entries on Add
body: <p>My data has a many-to-many relation between <code>Exhibitions</code> and <code>Markets</code>.
  When creating a new Exhibition, some existing markets should be assigned to it.
  I created a generic repository which looks like this:</p>
  
  <pre><code>public virtual TDto Create(TDto data)
  {
          TEntity entity = ToEntity(data);
          DbEntityEntry&lt;TEntity&gt; dbEntity = Context.Entry&lt;TEntity&gt;(entity);
          dbEntity.State = EntityState.Added;
          UpdateReferences(data, dbEntity);
          Context.SaveChanges();
          data = ToModel(dbEntity.Entity);
          return data;
  }
  </code></pre>
  
  <p>The idea is to allow each concrete repository to define it's own handling for updating it's references to other entities.</p>
  
  <pre><code>protected override void UpdateReferences(Exhibition model, DbEntityEntry&lt;Model.EventManagement.Exhibition&gt; entity)
  {
      entity.Entity.Markets = new List&lt;Model.EventManagement.Market&gt;();
      foreach (var market in model.Markets)
      {
          var marketEntity = Context.Markets.Single(m =&gt; m.Id == market.Id);
          entity.Entity.Markets.Add(marketEntity);
      }
  }
  </code></pre>
  
  <p>The problem that occures is, that the associated markets are duplicated when i create a new Exhibition with markets that already exist. My Context uses the following setup:</p>
  
  <pre><code>Configuration.LazyLoadingEnabled = false;
  Configuration.ProxyCreationEnabled = false;
  </code></pre>
  
  <p>So, my question is how to convince EF to associate the existing markets, instead of creating duplicates?</p>
  
  <p>I read a lot about using ID properties alongside navigation properties to avoid this kind of problems, but with many-to-many relations this does not seem to be an option.</p>