2013-07-18 68 views
1

我有兩個1:1關係的表。我使用實體框架的模型第一方法創建它們。現在我想要刪除一條記錄,但是我不能從一個表中刪除,而不能從另一個表中刪除,當我嘗試出現以下異常時:實體框架無法刪除與關係的對象

'正在從AssociationSet'FK_lm_ab_profile_lm_profile_master'添加或刪除關係。由於基數限制,還必須添加或刪除相應的'lm_ab_profile'。'

我有一個關係到ABProfile的個人資料表,我想從個人資料和AbProfile中刪除。它們都使用PROFILE_ID作爲PK,和ABProfile已PROFILE_ID爲FK

我的代碼:

 //Get the old profile to see if one already exists 
      var oldProfile = context.lm_profile_master.FirstOrDefault(p => p.profile_id.Equals(profileID)); 

      lm_ab_profile ab = new lm_ab_profile(); 

      //Check to see if user doesn't already exist 
      if (oldProfile != null) 
      { 

        //try and specify the relationship between profile and ABProfile using profileID 
        oldProfile.lm_ab_profileReference.EntityKey = new System.Data.EntityKey("luminusEntities.lm_ab_profile", "profile_id", profileID);  


        //remove found object from the database and persist changes 

        context.DeleteObject(oldProfile); 
        context.SaveChanges(); 
       } 

如何指定,當我從一個刪除記錄的兩個表是相關的,對方記錄得到刪除也...我設置我的表模型上的層疊功能。

回答

0

你描述的情況是表之間的約束。你試圖影響一致性。

看這個Delete an object and all of its related entities in Entity Framework並定義ON DELETE CASCADE

+0

是的,我已經設置了,但是當我嘗試刪除表要求我先指定與FK表,在這種情況下ABprofile參考來分析大師null ...這就是我想要在上面存檔的東西。 – Ndupza

+0

我不確定我是否正確理解它。 但是,如果您正確設置ON DELETE ACTION,則ABprofile對MasterProfile具有空引用是不可能的。 也許你設置ON DELETE ACTION = SET NULL? 我不是一個實體框架用戶,但我認爲它是數據庫層的問題。 –

+0

看起來像我的對象狀態管理器沒有正確組織,一直在調試,但在這個玉米中找不到東西 – Ndupza