Click here to Skip to main content
15,949,741 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi,
I am using entity data model and i have master-detail scenario.(Patient-PatientAddresses)

Everything is going on fine if i am updating any data either in master table or detail table.

But when i am going to insert a new detail record while updating master entity, it gives me following error :
"An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."

I googled so much, but not getting proper idea.

Here is my code :

using (var context = new Entities())
            {
                try
                {
                    var record = (from p in context.Patient.Include("PatientAddress")
                                  where p.PatientId == patient.PatientId
                                  select p).FirstOrDefault();
                    
                    if (record == null)
                    {
                        context.AddToPatient(patient);
                    }
                    else
                    {
                        foreach (var item in patient.PatientAddress)
                        {
                            if (item.EntityKey == null)
                            {
                                context.AddToPatientAddress(item); // <--Throws Exception here.
                                continue;
                            }
                            context.ApplyPropertyChanges("PatientAddress", item);
                        }
                        context.ApplyPropertyChanges("Patient", patient);
                    }
                    context.SaveChanges();
                    return true;
                }
                catch
                {
                    return false;
                }
            }


Any suggessions is appreciated.
Posted
Updated 2-Feb-10 18:16pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900