2011-07-08 58 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