title: Error : An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key
body: <p>I am new to entity framework.</p>
  
  <p>I have searched on this site and on google before asking this question and everywhere I found different answers. But my problem is not solved, so I am asking this question.</p>
  
  <p>I get the above mentioned error while I try to delete a record.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>using (Lab_Lite_Entities db = new Lab_Lite_Entities())
  
  
  {
  
       var HaemogramsCorrespondingToPatient = (from h in db.Haemograms
                                               join m in db.MasterPatientHaemograms
                                               on h.HaemogramID equals m.HaemogramID
                                               where m.PatientID == SelectedPatient.PatientID
                                               select h);
       foreach (Haemogram haemogram in HaemogramsCorrespondingToPatient)
       {
            if (db.Entry(haemogram).State == System.Data.EntityState.Detached)
                db.Haemograms.Attach(haemogram);
            db.Haemograms.Remove(haemogram);
            db.Entry(haemogram).State = EntityState.Deleted;
       }
  
       var entry = db.Entry(SelectedPatient);
       if (entry.State == System.Data.EntityState.Detached)
           db.Patients.Attach(SelectedPatient); //I get error here
       db.Patients.Remove(SelectedPatient);
       db.SaveChanges();
  }
  </code></pre>
  
  <p>Here is the relationship between the tables:</p>
  
  <p><img src="https://i.stack.imgur.com/ESwmY.jpg" alt="enter image description here"></p>
  
  <p><strong>Note: Please note that Cascade delete is on in sql server.</strong></p>
  
  <p><strong>Edit</strong></p>
  
  <p>I have also noticed something strange.</p>
  
  <p>When I create a patient and then try to delete the <code>CurrentPatient</code> object using the above mentioned code, I get the above mentioned error.</p>
  
  <p>But when I create a patient and then restart the program and then I try to delete the <code>CurrentPatient</code> object, then it is deleted without any problems.</p>