views:

425

answers:

1

I'm having a problem trying to add an object to an object context in Entity Framework.

Here is the 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();

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 ?

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.

Pierre

+2  A: 

I found the solution myself. It may be usefull for someone stuck on this stupid thing... It is just because in the database iteself the ID field was not set to AUTOINCREMENT... Changing this and updating the model.edmx solved the problem. Sorry for disturbing you with this !!!!!

pierre