本文介绍了尝试使用ObjectContext更新角色状态.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public void UpdateUserToRoles(string[] usernames, string[] roleNames)
{
string[] allRoles = GetAllRoles();
IEnumerable<string> roles = allRoles.Intersect(roleNames);
if (roles.Any())
{
//RemoveUsersFromRoles(usernames, roleNames);
using (var db = new EEGScreeningEntities())
{
List<int> mlist = (from m in db.aspnet_Users
where usernames.Contains(m.UserName)
select m.UserId).ToList();
List<int> glist = (from g in db.aspnet_Roles
where roleNames.Contains(g.RoleName)
select g.RoleId).ToList();
var mglist = (from m in mlist from g in glist select new User_In_Roles {UserId = m, RoleId = g}).FirstOrDefault();
db.SaveChanges();
}
得到此错误
违反主键约束"PK_User_In_Roles".无法在对象"dbo.User_In_Roles"中插入重复键.重复的键值为(26).
该声明已终止.
我正在尝试更新或更改用户角色.
get this error
Violation of PRIMARY KEY constraint ''PK_User_In_Roles''. Cannot insert duplicate key in object ''dbo.User_In_Roles''. The duplicate key value is (26).
The statement has been terminated.
I am trying to update or change the user role.
推荐答案
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
string[] allRoles = GetAllRoles();
IEnumerable<string> roles = allRoles.Intersect(roleNames);
if(roles.Any())
{
//RemoveUsersFromRoles(usernames, roleNames);
using (var db = new EEGScreeningEntities())
{
List<int> mlist = (from m in db.aspnet_Users
where usernames.Contains(m.UserName)
select m.UserId).ToList();
List<int> glist = (from g in db.aspnet_Roles
where roleNames.Contains(g.RoleName)
select g.RoleId).ToList();
var mglist = (from m in mlist from g in glist select new User_In_Roles {UserId = m, RoleId = g }).FirstOrDefault();
db.User_In_Roles.Attach(mglist);
db.ObjectStateManager.ChangeObjectState(mglist, EntityState.Modified);
db.SaveChanges();
}
}
}
这篇关于尝试使用ObjectContext更新角色状态.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!