title: c# Adding a new object to an object context returns "error occurred while updating the entries", duplicate entry for primary key
body: <p>I'm having a problem trying to add an object to an object context in Entity Framework.</p>
  
  <p>Here is the code :</p>
  
  <pre><code>//related object ids are retrieved from another context.
  //since I thought the problem could be linked to object loaded in this context, I tried to
  //close it and start on a fresh object context... 
  int idetab = currentEtab.Id;
  long idnivcycle = selectedNivcycle.id_nivcycle;
  long idanscol = AnneeScolaireEnCours.id_annee_scolaire;
  //and this context is closed
  context.Dispose();
  
  
  //This is the new object context
  objectcontextEntities ctest = new objectcontextEntities();
  //from where I retrieve all the objects I want to link to the object I want to create :            
  Nivcycle niv = ctest.Nivcycles.Where("it.id_nivcycle=@id", new ObjectParameter("id", idnivcycle)).First();
  Etablissement eta = ctest.Etablissements.Where("it.Id=@id", new ObjectParameter("id", Convert.ToInt32(idetab))).First();
  annee_scolaire an = ctest.annee_scolaire.Where("it.en_cours = @id", new ObjectParameter("id", Convert.ToSByte(true))).First();
  // Now I try to create my new object           
  Composante co = new Composante();
  co.Nom = "test";
  co.Nivcycle = niv;
  co.Etablissement = eta;
  co.AnneeScolDeb = an;
  ctest.AddToComposantes(co);
  ctest.SaveChanges();
  ctest.Dispose();
  </code></pre>
  
  <p>On SaveChanges(), I receive an UpdateException, saying that there is a duplicate entry '0' for Key 'PRIMARY'.
  It is true that I already have an object in my "Composantes" with id=0. And if I delete it, I can at least create one object with ID=0. What I don't understand is that when a new object is added to the context, why doesn't it take the next available ID ???? This is exactly the same error that was happening before I tried to create this object in a new context.... This is maybe because of a missing paramter in my model.edmx ? Is there a way somewhere to force the attribution of a new id to the newly created object ?</p>
  
  <p>I'm connecting to the mysql database using an entity Framework Model using Devart dot.connector to connect to the database.
  Thanking all of you in advance for your reply to this simple question.</p>
  
  <p>Pierre</p>