从实体框架中的集合中删除项目

时间:2014-03-27 12:28:25

标签: sql linq entity-framework

我有如下功能:

IEnumerable<Group> GetAllChildren(int parentID)
{
    using (Entities db = new Entities())
    {
        var result = (from x in db.Groups
                      where x.ParentID == parentID
                      select x).ToList();
        foreach (Group child in result.ToList())
        {
            result.AddRange(GetAllChildren(child.GroupID));
        }
        return result;
    }
}

在上面的函数中,如果我传递一个组名,我会得到所有级别的所有孩子。 它按预期工作。

现在我的查询类似于:

GroupNamesWithCorrespondingEffects 
    = new ObservableCollection<GroupNameWithCorrespondingEffect>
                (from g in db.Groups
                 select new GroupNameWithCorrespondingEffect
                            {
                                GroupID = g.GroupID,
                                GroupName = g.GroupName,
                                CorrespondingEffect = g.Master_Effects.Effect
                            }
                );

以上查询将为我提供所有组。

现在,我要删除GroupNamesWithCorrespondingEffects中属于group with id == 25子项的所有群组。

我在第二次查询中尝试了.Remove(GetAllChildren(25))。但我得到了以下错误。

  

Collection.Remove(GroupNameWithCorrespondingEffect)有一些无效的参数。

1 个答案:

答案 0 :(得分:1)

希望这能帮到你:

var childs = GetAllChildren(25).ToList();
var childIDList = childs.select(u => u.GroupID).ToList();

GroupNamesWithCorrespondingEffects = GroupNamesWithCorrespondingEffects
    .Where(u => !childIDList.Contains(u.GroupID)).ToList();