我有一个方法可以更新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...
行。即使我在groupIds
中有一个Guids集合与数据库中代表RecipientGroup
对象的Guids匹配,toAdd
也总是计算为空集合。我认为Contains()
函数适用于这种情况;有人可以解释我是否做错了什么?
答案 0 :(得分:1)
您应该从数据库中加载要添加的RecipientGroup
(我猜是Context.RecipientGroups
),而不是从要添加它们的集合中加载entity.RecipientGroups
代码示例中的{{1}} )。