实体框架通过外键查找实体

时间:2012-08-22 14:58:49

标签: entity-framework ef-code-first poco

我假设这是面包&大多数黄油..

我有角色,权限和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来移除给定的RolePermission,基于传入的RoleID和PermissionId。

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

任何指导? 非常感谢

1 个答案:

答案 0 :(得分:0)

由于您将RolePermission公开为实体(对于多对多关系而言有点不寻常),您应该只能在连接表中查询记录并将其删除:< / p>

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