找到参与0相关“角色”的实体。 1'角色'是预期的

时间:2012-06-18 14:51:38

标签: c# wpf entities

我有3张桌子

Roles
------
RoleId(PK)
RoleName
RoleDescription

CustomPermissions
-----------------
PermissionId(PK)
PermissionName
PermissionDescription

RolePermissionMappings
------------------------
RoleId (PK)
PermissionId(PK)
Role_RoleId(FK)
CustomPermission_PermissionId(FK)

我个人能够为Roles和CustomPermissions表添加值。 当我试图在RolePermissionMappings表中映射值时,我收到此错误。

Entities in 'RolePermissionMappingContainer.RolePermissionMappings' 
participate in the 'RoleRolePermissionMapping' relationship. 0 related 'Role' were found. 1 'Role' is expected.

角色拥有多项权限,他们必须在RolePermissionMappings表中进行映射

RoleId   PermissionId
------   ------------
  2          2
  2          4
  2          5
  2          8
  2          10

我的代码

bool ICustomPermissions.AddPermissionsToRole(RoleDataContract role, List<PermissionDataContract> permissions)
{
    using(_context = new RolePermissionMappingContainer())
    {
        RolePermissionMapping rpm = new RolePermissionMapping();
        {
            rpm.RoleId =  role.RoleId;

            foreach (PermissionDataContract pdc in permissions)
            {
                rpm.PermissionId =  pdc.PermissionId;
                //_context.RolePermissionMappings.AddObject(rpm);
                _context.RolePermissionMappings.AddObject(rpm);
                _context.SaveChanges();
            }
        }
    }
    return true;
}

如果我遇到错误,请纠正我。

1 个答案:

答案 0 :(得分:0)

RolePermissionMapping中的每个PermissionDataContract创建permissions的新实例:

bool ICustomPermissions.AddPermissionsToRole(RoleDataContract role, List<PermissionDataContract> permissions)
    {
       using(_context = new RolePermissionMappingContainer())
       {

               foreach (PermissionDataContract pdc in permissions)
               {

                   RolePermissionMapping rpm = new RolePermissionMapping()
                   {
                       RoleId = role.RoleId,
                       PermissoinId = pdc.PermissionId
                   }

                   _context.RolePermissionMappings.AddObject(rpm);
                   _context.SaveChanges();
               }
       }
       return true;
    }