我已经写了一个扩展方法来添加项目到(EF)EntityCollection。我收到了一个有趣的错误,说我收集的IEnumerable(“items”)在foreach的第一个循环之后被修改了。当我将项目变成items.ToList()(如下面的代码)时,它工作正常。C#修改IEnumerable之谜,什么是修改我的IEnumerable?
我完全理解做ToList()会产生foreach将在其上运行的项目的副本。
我不明白什么是修改IEnumerable,当我对它进行foreach。
更新:不知何故,似乎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);
}
'Remove'修改它,所以不会添加。 – vcsjones 2012-01-09 14:10:07
@vcsjones虽然这是事实,但在这种情况下并不那么简单。 – 2012-01-09 14:12:58
你的情况是'items == collection'吗? – 2012-01-09 14:26:53