我正在尝试使用以下方法将用户角色列表从一个用户复制到另一个用户:
public bool CopyUsersRoles(Guid copyFromUserId, Guid copyToUserId)
{
//Delete existing roles for user
var rolesToDelete = context.UserApplicationRoles.Where(x => x.UserID == copyToUserId);
foreach (var u in rolesToDelete)
{
context.UserApplicationRoles.DeleteObject(u);
}
var rolesToAdd = context.UserApplicationRoles.Where(x => x.UserID == copyFromUserId)
.ToList();
for(int i = 0; i < rolesToAdd.Count; i++)
{
rolesToAdd[i].UserID = copyToUserId;
}
foreach (var u in rolesToAdd)
{
context.UserApplicationRoles.AddObject(u);
}
context.SaveChanges();
}
分配新的UserId
时,我收到以下异常:
属性“UserID”是对象密钥信息的一部分,无法修改。 在System.Data.Objects.EntityEntry.VerifyEntityValueIsEditable(StateManagerTypeMetadata typeMetadata,Int32 ordinal,String memberName)
我原本以为ToList()会阻止这个......
实现这一目标的正确方法是什么?
编辑 - 课程详情:
我看到旧桌上没有PK设置。我假设手动将PK设置为UserApplicationRoleId将修复此问题。
UserId看起来像这样:
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Guid UserID
{
get
{
return _UserID;
}
set
{
if (_UserID != value)
{
OnUserIDChanging(value);
ReportPropertyChanging("UserID");
_UserID = StructuralObject.SetValidValue(value);
ReportPropertyChanged("UserID");
OnUserIDChanged();
}
}
}
答案 0 :(得分:0)
这是问题所在:
var rolesToAdd = context.UserApplicationRoles
.Where(x => x.UserID == copyFromUserId)
.ToList();
....
foreach (var u in rolesToAdd)
{
context.UserApplicationRoles.AddObject(u);
}
您正在引用已在DB / EF中的对象。您必须克隆这些并将克隆添加到EF。
答案 1 :(得分:0)
结束让这个以非常讨厌的方式工作(遗留数据库没有自动递增的PK :(
var copyToUser = this.GetUser(copyToUserId);
List<UserApplicationRole> userApplicationRoles = new List<UserApplicationRole>();
int startingId = Convert.ToInt32(isignonContext.UserApplicationRoles.OrderByDescending(u => u.UserApplicationRoleId).FirstOrDefault().UserApplicationRoleId) + 1;
foreach (var u in userApplicationRolesToAdd)
{
UserApplicationRole userApplicationRole = new UserApplicationRole
{
UserApplicationRoleId = startingId,
UserID = copyToUser.UserId,
UserGroupId = copyToUser.ParentId.Value,
ApplicationRoleId = u.ApplicationRoleId,
ExpiryDate = u.ExpiryDate,
IsEnabled = u.IsEnabled
};
userApplicationRoles.Add(userApplicationRole);
startingId++;
}