[英]EF many-to-many madness
我有一種更新EF中的ReportRecipient
對象的方法。 原語可以正常工作; 當嘗試使用RecipientGroups
對象管理M2M關系時,頭痛就來了。
請看下面的代碼:
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...
行上。 即使我的GUID在收集groupIds
匹配代表的GUID是RecipientGroup
數據庫中的對象, toAdd
始終計算為一個空的集合。 我認為Contains()
函數適用於這種情況; 有人可以解釋我做錯了什么嗎?
您應該從數據庫中加載要添加的RecipientGroup
(我猜是Context.RecipientGroups
),而不是從要添加它們的集合中加載(代碼示例中的entity.RecipientGroups
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.