C#修改IEnumerable的谜团,修改我的IEnumerable是什么?

seb*_*aan 5 c# ienumerable extension-methods

我编写了一个扩展方法来向(EF)EntityCollection添加项目.我收到一个有趣的错误,说我的IEnumerable("items")集合在foreach的第一个循环之后被修改了.当我将项目转换为items.ToList()(如下面的代码中),它工作正常.

我完全理解,执行ToList()将生成foreach将在其上运行的项目的副本.

我不明白的是当我对它进行预测时修改IEnumerable的是什么.

更新:不知何故,似乎items变量与collections变量相同?

更新2:我认为收集和实体可能会受到EF实体跟踪的影响,但我仍然无法理解原因

用法:

ssp.ServiceAreas.ReplaceCollection(model.ServiceAreas);

这是我的扩展方法:

    public static void AddOrUpdate<TEntity>(this EntityCollection<TEntity> collection, IEnumerable<TEntity> items)
        where TEntity : EntityObject, IProjectIdentity<int>, new()
    {
        foreach (var item in items.ToList())
            collection.AddOrUpdate(item);
    }

    public static void AddOrUpdate<TEntity>(this EntityCollection<TEntity> collection, TEntity item)
        where TEntity : EntityObject, IProjectIdentity<int>, new()
    {
        if (item.ID > 0 && collection.Any(c => c.ID == item.ID))
            collection.Remove(collection.First(c => c.ID == item.ID));
        // For now, the Remove NEVER gets hit

        collection.Add(item);
    }
Run Code Online (Sandbox Code Playgroud)

KMa*_*Man 4

collection.Remove(collection.First(c => c.ID == item.ID)); 
Run Code Online (Sandbox Code Playgroud)

您正在迭代的集合中删除。

  • 但迭代是通过不同的集合(项目) (2认同)