我有一个表,供用户担任角色,它只是用户可以使用的两个角色之一。
CREATE TABLE [dbo].[webpages_UsersInRoles] (
[UserId] INT NOT NULL,
[RoleId] INT NOT NULL,
CONSTRAINT [PK_dbo.webpages_UsersInRoles] PRIMARY KEY CLUSTERED ([UserId] ASC, [RoleId] ASC),
CONSTRAINT [FK_dbo.webpages_UsersInRoles_dbo.webpages_Roles_RoleId] FOREIGN KEY ([RoleId]) REFERENCES [dbo].[webpages_Roles] ([RoleId]) ON DELETE CASCADE
);
CREATE TABLE [dbo].[webpages_Roles] (
[RoleId] INT IDENTITY (1, 1) NOT NULL,
[RoleName] NVARCHAR (MAX) NULL,
[webpages_Membership_UserId] INT NULL,
CONSTRAINT [PK_dbo.webpages_Roles] PRIMARY KEY CLUSTERED ([RoleId] ASC),
CONSTRAINT [FK_dbo.webpages_Roles_dbo.webpages_Membership_webpages_Membership_UserId] FOREIGN KEY ([webpages_Membership_UserId]) REFERENCES [dbo].[webpages_Membership] ([UserId])
);
在我的代码中,我尝试从UsersInRoles
删除用户但是我一直从我的tempdata中收到错误:
角色出错。必须传递的主键值数量 匹配实体上定义的主键值的数量。参数 name:键值
这是我正在使用的代码:
string pid = form["pid"];
try
{
if (ModelState.IsValid)
{
Provider cprovider = _db.Providers.Find(pid);
var UserId = cprovider.UserProfileId;
try
{
webpages_Membership cmembership = _db.webpages_Memberships.Find(UserId);
_db.webpages_Memberships.Remove(cmembership);
_db.SaveChanges();
}
catch (Exception ex)
{
TempData["Message"] = "Error occured with membership." + ex.Message;
}
try
{
UserProfile cprofile = _db.UserProfiles.Find(UserId);
_db.UserProfiles.Remove(cprofile);
_db.SaveChanges();
}
catch (Exception ex)
{
TempData["Message"] = "Error occured with profile." + ex.Message;
}
try // this code is causing an exception
{
webpages_UsersInRoles croles = _db.webpages_UsersInRoles.Find(UserId);
_db.webpages_UsersInRoles.Remove(croles);
_db.SaveChanges();
}
catch (Exception ex)
{
TempData["Message"] = "Error occured with roles." + ex.Message;
}
cprovider.UserProfileId = null;
cprovider.PendingActivation = null;
cprovider.Activated = null;
cprovider.Email = null;
_db.Entry(cprovider).State = EntityState.Modified;
_db.SaveChanges();
}
}
答案 0 :(得分:2)
您的Find
方法调用缺少参数 - 它需要UserId
和RoleId
:
_db.webpages_UsersInRoles.Find(UserId, RoleId)
如果您的目标是删除所有用户的角色,请不要使用find方法,请使用Where
w / RemoveRange
:
var croles = _db.webpages_UsersInRoles.Where( uir => uir.UserId == UserId );
_db.webpages_UsersInRoles.RemoveRange( croles );