QEx
QEx

Reputation: 81

SQL Error: foreign key value cannot be inserted because a corresponding primary key value does not exist

I am creating a Manage Roles - Admin page using standard WebSecurity functionality.

I'm getting the this error

Foreign key value cannot be inserted because a corresponding primary key value does not exist. [Foreign key constraint name = fk_UserId]

on the following line of code:

if(!Roles.IsUserInRole(userNames[0], roleNames[0])){
       Roles.AddUsersToRoles(userNames, roleNames);
}

My understanding that the individual tables should be linked with a userId column. And they are. I am using WebMatrix 2 and the Razor framework for the development.

Any ideas or solutions by you SQL Masterminds? Thanks a lot!

Below is the code fragment of how I am going about it!

 @{
    var roleName = "";
    string[] userNames = new string[1];
    string[] roleNames = new string[1];

    var db = Database.Open("ResearchA");
    var selectQueryString = "SELECT UserId, username FROM [usernames]";

  if(IsPost){

    // Create new role
    if(!Request["buttonCreateRole"].IsEmpty()){
      roleName=Request["textRoleName"];

      if(!Roles.RoleExists(roleName) && !roleName.IsEmpty()){
        Roles.CreateRole(roleName);
      }
    } 

    // Delete role

    if(!Request["buttonDeleteRole"].IsEmpty()){
      roleName=Request["textRoleName"];

      if(Roles.GetUsersInRole(roleName).Length == 0 && !roleName.IsEmpty()){
        Roles.DeleteRole(roleName, true); 
      }
    } 

    // Add user to role

    if(!Request["buttonAddUserToRole"].IsEmpty()){
      userNames[0] = Request["selectUserName"];
      roleNames[0] = Request["selectRoleName"];

      if(!Roles.IsUserInRole(userNames[0], roleNames[0])){
       Roles.AddUsersToRoles(userNames, roleNames);
      }
    }

    // Delete user from role

    if(!Request["buttonDeleteUserFromRole"].IsEmpty()){
      userNames[0] = Request["selectUserName"];
      roleNames[0] = Request["selectRoleName"];

      if(Roles.IsUserInRole(userNames[0], roleNames[0])){
        Roles.RemoveUsersFromRoles(userNames, roleNames);
      }
    } 
  }
}

Upvotes: 0

Views: 1388

Answers (1)

Bryan Hunter
Bryan Hunter

Reputation: 627

Not sure, but it sounds like you're attempting to create the User and Role tables by hand.

Have you tried running aspnet_regsql.exe? You can find it in your "%WINDIR%\Microsoft.NET\Framework\v4.0.30319\" directory. It will open a wizard to create the appropriate tables using the SQL scripts in the same "%WINDIR%\Microsoft.NET\Framework\v4.0.30319\" directory.

Upvotes: 0

Related Questions