簡體   English   中英

錯誤:ObjectStateManager中已經存在具有相同鍵的對象。 ObjectStateManager無法使用相同的鍵跟蹤多個對象

[英]Error : An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key

我是實體框架的新手。

在問這個問題之前,我已經在這個網站和google上搜索過,到處都找到了不同的答案。 但是我的問題沒有解決,所以我問這個問題。

我在嘗試刪除記錄時收到上述錯誤。

這是我的代碼:

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();
}

這是表之間的關系:

在此處輸入圖片說明

注意:請注意,級聯刪除在SQL Server中處於啟用狀態。

編輯

我也注意到了一些奇怪的事情。

當我創建一個患者,然后嘗試使用上述代碼刪除CurrentPatient對象時,出現上述錯誤。

但是,當我創建一個患者,然后重新啟動程序,然后嘗試刪除CurrentPatient對象時,便可以毫無問題地將其刪除。

我只能想象,如果SelectedPatient包含MasterPatientHaemogram類型的引用對象以及這些再次引用Haemogram類型的對象,則會發生此錯誤。 當您附加SelectedPatient (顯然是一個分離的實體)時,將附加整個對象圖,包括Haemogram對象, Haemogram對象可能具有與您在HaemogramsCorrespondingToPatient查詢中已加載的鍵相同的鍵。 這將導致異常。

最簡單,最安全的解決方案是根本不嘗試附加分離的SelectedPatient ,而是從數據庫加載副本並刪除此實體:

//...
var patient = db.Patients.Find(SelectedPatient.PatientID);
db.Patients.Remove(patient);
db.SaveChanges();

如果您不喜歡使用Find查詢數據庫,請使用正確的密鑰創建一個存根實體:

//...
var patient = new Patient { PatientID = SelectedPatient.PatientID };
db.Patients.Attach(patient);
db.Patients.Remove(patient);
db.SaveChanges();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM