2012-03-21 67 views
0

我有一種方法更新EF中的ReportRecipient對象。基元工作正常;當試圖管理與物品對象的M2M關係時,頭疼就出現了。EF多對多的瘋狂

請看看下面的代碼:

public IReportRecipient ModifyRecipientWithGroupAssignments(IEnumerable<Guid> groupIds, IReportRecipient recipient) 
    { 
     var entity = Context.ReportRecipients 
      .Include("RecipientGroups") 
      .FirstOrDefault(e => e.ReportRecipientId == recipient.ReportRecipientId) 
      .FromIReportRecipient(recipient); 

     var toRemove = entity.RecipientGroups 
      .Where(e => !groupIds.Contains(e.GroupId)) 
      .ToList(); 

     //remove group assignments that no longer apply 
     foreach (var group in toRemove) 
     { 
      if (group != null) 
      { 
       entity.RecipientGroups.Attach(group); 
       entity.RecipientGroups.Remove(group); 
      } 
     } 

     var toAdd = entity.RecipientGroups 
      .Where(e => groupIds.Contains(e.GroupId)) 
      .ToList(); 

     //add new groups that weren't there before 
     foreach (var group in toAdd) 
     { 
      if (group != null) 
      { 
       entity.RecipientGroups.Attach(group); 
      } 
     } 

     return entity; 
    } 

...我的問題是關於var ToAdd...線。即使我在groupIds中有一組Guid,它們與數據庫中的代表RecipientGroup對象的Guids匹配,toAdd總是計算爲一個空集合。我認爲Contains()函數適用於這種情況;有人能解釋我是否做錯了什麼?

回答

1

您應該從數據庫中加載想要添加的RecipientGroup(我想是Context.RecipientGroups),而不是您想要添加它們的集合(代碼示例中的entity.RecipientGroups)。

+0

Doh!我是個白癡。謝謝。 – 2012-03-22 01:28:08