2012-09-20 49 views
0

我試圖從一個用戶複製用戶的角色列表到另一個方法的集合:複製的entites

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,字符串成員名稱)

我會認爲ToList()會阻止這個...

什麼正確的方法來實現這一點?

編輯 - 類細節:

enter image description here

我看到有對遺留表中沒有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(); 
      } 
     } 
    } 
+0

您需要將角色添加到用戶角色的集合,在不改變用戶ID !!! – gdoron

+0

我需要採取現有的角色,使用新的用戶ID創建他們的副本,然後將新的ID添加到集合中。我可能在這裏丟失了一些非常明顯的東西! – woggles

+1

你可以發佈'角色' class? – Eranga

回答

0

最終獲得這一個非常討厭的工作方式(傳統DB沒有自動遞增的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++; 
      }  
0

這就是問題所在:

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

    .... 

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

您參照了已在DB/EF對象。您必須對這些進行克隆並向EF添加克隆。