Reputation: 1705
The INSERT statement conflicted with the FOREIGN KEY constraint "fk_RoleId". The conflict occurred in database "mydb", table "dbo.webpages_Roles", column 'RoleId'.
I'm not sure what is causing this issue, I've gone to dbo.webpages_UsersInRoles
and removed the FK constraints and it still comes down to this error. Not sure what to do here.
WebSecurity.CreateUserAndAccount(model.RegistrationInfo.UserName, model.RegistrationInfo.Password);
Roles.AddUserToRole(model.RegistrationInfo.UserName, level); //both strings
Adding them the right way but the database just won't accept these entries. here is the db schemas.
CREATE TABLE [dbo].[webpages_Roles] (
[RoleId] INT IDENTITY (1, 1) NOT NULL,
[RoleName] NVARCHAR (256) NOT NULL,
PRIMARY KEY NONCLUSTERED ([RoleId] ASC),
UNIQUE NONCLUSTERED ([RoleName] ASC)
);
CREATE TABLE [dbo].[webpages_UsersInRoles] (
[RoleId] INT NOT NULL,
[UserId] INT NOT NULL,
CONSTRAINT [PK_webpages_UsersInRoles] PRIMARY KEY CLUSTERED ([RoleId] ASC, [UserId] ASC),
CONSTRAINT [FK_webpages_UsersInRoles_UserProfile] FOREIGN KEY ([UserId]) REFERENCES [dbo].[UserProfile] ([UserId]),
CONSTRAINT [FK_webpages_UsersInRoles_webpages_Roles] FOREIGN KEY ([RoleId]) REFERENCES [dbo].[webpages_Roles]([RoleId])
);
I'm only able to manually entering integers as roleid and userid pairs.
I've seen this issue on other people's posts but no solution was to be found.
Upvotes: 0
Views: 631
Reputation: 154
Swap order of UserId and RoleId in webpages_UsersInRoles table. UserId shall be the first column.
Upvotes: 1
Reputation: 740
Make sure that you already have that role in your database. I think in your database that role isn't exists in webpages_roles table. That's why this problem occurred.
if (!Roles.RoleExists(newRoleName)) {
Roles.CreateRole(newRoleName)
};
You should do this before you assign roles.
Upvotes: 0