如何将多个用户批量添加到具有SQL Server LocalDb的角色

时间:2013-03-16 12:58:21

标签: sql-server

我有以下代码:

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

1 个答案:

答案 0 :(得分:0)

我也遇到过这个问题,似乎是addUserToRole将userID插入到roleID列,将Role ID插入UserID列,这意味着它找不到等于3的userId,从而给出错误信息。