EF多对多的疯狂

时间:2012-03-21 20:18:11

标签: c# entity-framework ienumerable

我有一个方法可以更新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()函数适用于这种情况;有人可以解释我是否做错了什么?

1 个答案:

答案 0 :(得分:1)

您应该从数据库中加载要添加的RecipientGroup(我猜是Context.RecipientGroups),而不是从要添加它们的集合中加载entity.RecipientGroups代码示例中的{{1}} )。

相关问题