Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从集合中删除实体_C#_Linq - Fatal编程技术网

C# 从集合中删除实体

C# 从集合中删除实体,c#,linq,C#,Linq,我有三张桌子;组、客户和组客户。组可以有许多客户,因此需要使用GroupCustomers表。在我的WinC窗体程序中,我试图使用Linq删除特定组的所有客户。这是我的代码,看起来很有效,但我认为我缺少了一些东西,使这个查询变得更小/更容易/更快速地读取和执行 Context.Groups.Where(g => g.Id == group.Id) .FirstOrDefault() .Custo

我有三张桌子;组、客户和组客户。组可以有许多客户,因此需要使用GroupCustomers表。在我的WinC窗体程序中,我试图使用Linq删除特定组的所有客户。这是我的代码,看起来很有效,但我认为我缺少了一些东西,使这个查询变得更小/更容易/更快速地读取和执行

Context.Groups.Where(g => g.Id == group.Id)
                        .FirstOrDefault()
                        .Customers.ToList()
                        .ForEach(gc =>
                            {
                                Context.Groups.Where(g => g.Id == group.Id)
                                                            .FirstOrDefault()
                                                            .Customers.Remove(gc);
                            });
Context.SaveChanges();

group.Id是一个传递到此方法的变量。

我认为您太拘泥于LINQ了。我会这样写:

 var group = Context.Groups.First(g => g.Id == group.Id); // if you're sure of existing
 foreach (var customer in group.Customers.ToList()) // ToList is required to avoid 'Collection was modified' exception, I think
      Context.Customers.Remove(customer);
 Context.SaveChanges();

编写查询以选择要删除的所有项目。您希望删除特定组中的所有客户。这将对应于为链接两者而创建的GroupCustomers。选择这些,然后删除它们

var toBeRemoved =
    from gc in Context.GroupCustomers
    where gc.GroupId == group.Id
    select gc;
foreach (var gc in toBeRemoved)
    Context.GroupCustomers.DeleteObject(gc);
Context.SaveChanges();
否则,你所拥有的在逻辑上是好的,但我会做一些调整。选择要从中删除客户的组,然后从组中删除客户。ToList.ForEach不应用作对ForEach的常规调用的替代


您正在从上下文中完全删除客户,而OP只是从特定的组中删除客户。@Rune,当得到一个组对象时,我枚举它的导航属性-group.customers。首先,您可以跳过Where并将谓词传递给FirstOrDefault。还要注意,FirstOrDefault可以返回null。我真的敦促你检查一下,或者先去看看,我认为这会给你一个更好/更可读的例外,以防一组人失踪。
var removeFromGroup = Context.Groups.FirstOrDefault(g => g.Id == group.Id);
foreach (var c in removeFromGroup.Customers)
    removeFromGroup.Remove(c);
Context.SaveChanges();