EF许多对许多的疯狂
本文关键字:许多 疯狂 EF | 更新日期: 2023-09-27 18:28:47
我有一个方法可以更新EF中的ReportRecipient
对象。基元工作良好;当试图管理与CCD_ 2对象的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
中有一个与表示数据库中RecipientGroup
对象的Guid匹配的Guid集合,toAdd
的计算结果也总是为空集合。我认为Contains()
函数适用于这种情况;有人能解释一下我是否做错了什么吗?
您应该从数据库加载要添加的RecipientGroup
(我想是Context.RecipientGroups
),而不是从要添加它们的集合(代码示例中的entity.RecipientGroups
)。