2011-07-08 53 views
0

比方說,有3個表:問題在多對多的關係EF4插入或更新

Category 
------------- 
CategoryID int 
Title   text 


Admin 
------------ 
AdminID  int 
FullName  text 


Permission 
------------ 
CategoryID int 
AdminID  int 
AllowAccess bit 

當我嘗試更新數據庫更改我得到了以下異常:

Unable to insert or update an entity because the principal end of the 'KiaNetModel.FK_Permissions_Admins' relationship is deleted. 

爲什麼?

的功能更新變化:

public static void SetPermissions(int[] cats, int userId, Entities context) 
     { 
      var premissions = from p in context.AdminPremissions where p.AdminID == userId select p; 
      // Clear all premissions... 
      foreach (var p in premissions) 
      { 
       p.AllowAccess = false; 
      } 

      foreach (var c in cats) 
      { 
       var es = from e in context.AdminPremissions where e.CategoryID == c && e.AdminID == userId select e; 
       // If any pre permission was found, set flag = true 
       if (es.Count() > 0) 
        es.First().AllowAccess = true; 

       // Otherwise add new one 
       else 
        context.AdminPremissions.AddObject(new AdminPremission() { AdminID = userId, CategoryID = c, AllowAccess = true }); 
      } 
     } 

這是一個Web應用程序,而當用戶標記的權限,我只能確定哪些權限設置,不是所有的人。

如果您有任何其他想法或更好的方式請告訴我。

回答

1

我認爲表的權限和管理員之間的關係已從實際數據庫或從實體模型中刪除。它是這種情況,那麼你必須再次創建這種關係。

+1

兩個關係都沒有被刪除。我看數據庫關係和模型,它們都存在。 – Jalal

-3

生成「Admin」表和「權限」刪除並創建腳本(使用數據 - 如果U有數據)。

然後執行它,如果U有關係重新創建它, Ur Prb必須解決。

+0

正如我在其他答案的評論中所說的,兩種關係都沒有被刪除: – Jalal

+0

foreach是罪魁禍首,您可以更新屬性,並在foreach中向Context添加新對象,只要確保不在循環內部調用SaveChanges(),否則會出現此錯誤 – mknopf