0

我假设这是大多数人的面包和黄油..

我有 Roles、Permissions 和 RolePermissions 实体来建模多对多关系。

public class RolePermission
{
    [Key]
    public int ID { get; set; }

    //[Key, ForeignKey("Role"), Column(Order = 0)]
    public int RoleID { get; set; }

    //[Key, ForeignKey("Permission"), Column(Order = 1)]
    public int PermissionID { get; set; }

    //Navigational Properties
    public virtual Role role { get; set; }
    public virtual Permission permission { get; set; }
}

我有一个 ActionResult 可以根据传入的 RoleID 和 PermissionId 删除给定的 RolePermission。

public ActionResult Remove(int Roleid, int Permissionid)
{
  RolePermission rolepermission = db.RolePermissions
    .Include(p => p.PermissionID == Permissionid)
    .SingleOrDefault(p => p.RoleID == Roleid);

  db.RolePermissions.Remove(rolepermission);
  db.SaveChanges();
  return RedirectToAction("Index");  
}

上面的 RolePermission rolepermission.. 语句失败

The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.
Parameter name: path

..我并不感到惊讶,因为它一开始就有一股代码味道。

我所追求的是相当于

Delete from RolePermission
Where RoleID = roleid
AND PermissionID = permissionid

有什么指导吗?非常感谢

4

1 回答 1

0

由于您将RolePermission公开作为一个实体(这对于多对多关系来说有点不寻常),您应该能够只查询连接表中的记录并将其删除:

public ActionResult Remove(int Roleid, int Permissionid)
{
    RolePermission rolepermission = db.RolePermissions
        .SingleOrDefault(rp => rp.RoleID == Roleid
                            && rp.PermissionID == Permissionid);

    if (rolepermission != null)
    {
        db.RolePermissions.Remove(rolepermission);
        db.SaveChanges();
    }
    return RedirectToAction("Index");  
}
于 2012-08-22T15:05:59.537 回答