我正在使用asp.net mvc4,c#和Entity Framework 5.我試圖創建一個用戶並將角色分配給用戶,同時使用簡單的會員(數據庫第一種方法),但得到以下錯誤在Roles.AddUserToRole("nuser", "Admin");
使用SimpleMembership的AddUserToRole時出現錯誤:INSERT語句與FOREIGN KEY約束衝突
INSERT語句衝突與外鍵約束 「FK_webpages_UsersInRoles_webpages_Roles」。衝突發生在 數據庫「DbClick2Eat」,表「dbo.webpages_Roles」,列'RoleId'。 該聲明已被終止。
這裏是我的代碼: -
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateUserByAdmin(RegisterModel register, string role)
{
try
{
if (Roles.RoleExists(role))
{
var model = register ?? new RegisterModel();
WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
if (WebSecurity.UserExists(model.UserName))
Roles.AddUserToRole("admin1", "Admin");
}
else
ModelState.AddModelError("NoRole", "Please select a role.");
var roles = Roles.GetAllRoles().ToList();
ViewBag.DeliveryArea = new SelectList(roles.Select(x => new { Value = x, Text = x }), "Value", "Text");
return View();
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", AccountController.ErrorCodeToString(e.StatusCode));
}
return View();
}
DB模式
CREATE TABLE [dbo].[webpages_Roles](
[RoleId] [int] IDENTITY(1,1) NOT NULL,
[RoleName] [nvarchar](256) NOT NULL,
CONSTRAINT [PK_webpages_Roles] PRIMARY KEY CLUSTERED
(
[RoleId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[webpages_UsersInRoles](
[RoleId] [int] NOT NULL,
[UserId] [int] NOT NULL,
CONSTRAINT [PK_webpages_UsersInRoles] PRIMARY KEY NONCLUSTERED
(
[RoleId] ASC,
[UserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
ALTER TABLE [dbo].[webpages_UsersInRoles] WITH CHECK ADD CONSTRAINT [FK_webpages_UsersInRoles_UserProfile] FOREIGN KEY([UserId])
REFERENCES [dbo].[UserProfile] ([UserId])
GO
ALTER TABLE [dbo].[webpages_UsersInRoles] CHECK CONSTRAINT [FK_webpages_UsersInRoles_UserProfile]
GO
ALTER TABLE [dbo].[webpages_UsersInRoles] WITH CHECK ADD CONSTRAINT [FK_webpages_UsersInRoles_webpages_Roles] FOREIGN KEY([RoleId])
REFERENCES [dbo].[webpages_Roles] ([RoleId])
GO
ALTER TABLE [dbo].[webpages_UsersInRoles] CHECK CONSTRAINT [FK_webpages_UsersInRoles_webpages_Roles]
- > 「管理」 是一個角色名
角色ID = 1,角色名=管理員
「管理」 角色在table.I存在無法修復它...需要幫助
請您提供角色表(DB計劃和管理記錄)以獲取更多信息? –
@stefchri,謝謝你的回覆。我已經添加了數據庫模式。 – NeoDeveloper