0

我有以下代码:

    WebSecurity.CreateUserAndAccount("r12345678", "abcdefgh", false);
    WebSecurity.CreateUserAndAccount("m12345678", "abcdefgh", false);
    System.Web.Security.Roles.CreateRole("Author");
    System.Web.Security.Roles.CreateRole("Admin");
    System.Web.Security.Roles.CreateRole("Super");
    System.Web.Security.Roles.AddUserToRole("r12345678", "Author");
    System.Web.Security.Roles.AddUserToRole("r12345678", "Admin");
    System.Web.Security.Roles.AddUserToRole("r12345678", "Super");
    System.Web.Security.Roles.AddUserToRole("m12345678", "Author");
    System.Web.Security.Roles.AddUserToRole("m12345678", "Admin");

前 5 行运行良好,但是当涉及到这一行时:

    System.Web.Security.Roles.AddUserToRole("r12345678", "Super");

我得到以下信息:

The INSERT statement conflicted with the FOREIGN KEY constraint "webpages_Roles_UserProfiles_Target". The conflict occurred in database "T12345", table "dbo.UserProfile", column 'UserId'.
The statement has been terminated.

我不明白为什么会这样。我有一个 100% 新鲜的数据库。事实上,我删除了数据库并重新创建。这是我的 SQL 定义:

CREATE TABLE [dbo].[webpages_UsersInRoles] (
    [RoleId] INT NOT NULL,
    [UserId] INT NOT NULL,
    PRIMARY KEY CLUSTERED ([RoleId] ASC, [UserId] ASC),
    CONSTRAINT [webpages_Roles_UserProfiles_Source] FOREIGN KEY ([RoleId]) REFERENCES [dbo].[webpages_Roles] ([RoleId]) ON DELETE CASCADE,
    CONSTRAINT [webpages_Roles_UserProfiles_Target] FOREIGN KEY ([UserId]) REFERENCES [dbo].[UserProfile] ([UserId]) ON DELETE CASCADE
);

我的 UserProfile 表包含:

UserId  UserName
1   r12345678
2   m12345678

我的 UsersInRoles 表包含:

RoleId  UserId
1       1
1       2

我的角色表包含​​:

1   Author
2   Admin
3   Super

有谁知道为什么会触发外键约束

更新:

请注意,我尝试了以下方法,但这也不起作用。它给出了类似的错误:

Roles.AddUsersToRoles(new[] {"r12345678"}, new[] {"Author","Admin","Super"});
Roles.AddUsersToRoles(new[] {"m12345678" }, new[] { "Author", "Admin", "Super" });
4

1 回答 1

0

我也遇到过这个问题,似乎 addUserToRole 将 userID 插入到 roleID 列中,将 Role ID 插入到 UserID 列中,这意味着它找不到等于 3 的 userId 并因此给出错误消息.

于 2013-04-16T13:04:34.457 回答