EF多对多的疯狂
问题描述:
我有一种方法更新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()
函数适用于这种情况;有人能解释我是否做错了什么?
答
您应该从数据库中加载想要添加的RecipientGroup
(我想是Context.RecipientGroups
),而不是您想要添加它们的集合(代码示例中的entity.RecipientGroups
)。
Doh!我是个白痴。谢谢。 – 2012-03-22 01:28:08