0

我正在尝试使用以下方法将用户角色列表从一个用户复制到另一个用户:

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 类型元数据,Int32 序数,字符串成员名称)

我原以为 ToList() 会阻止这种情况......

实现这一目标的正确方法是什么?

编辑 - 课程详情:

在此处输入图像描述

我看到遗留表上没有设置 PK。我假设手动将 PK 设置为 UserApplicationRoleId 将解决此问题。

用户 ID 看起来像这样:

    [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();
            }
        }
    }
4

2 回答 2

0

这就是问题:

  var rolesToAdd = context.UserApplicationRoles
  .Where(x => x.UserID == copyFromUserId)                             
  .ToList();  

   ....

  foreach (var u in rolesToAdd)
  {
    context.UserApplicationRoles.AddObject(u);
  } 

您正在引用 DB/EF 中已经存在的对象。您必须克隆这些并将克隆添加到 EF。

于 2012-09-20T07:18:21.003 回答
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++;
            }     
于 2012-09-20T07:49:47.967 回答