我一直在现场处理这个异常。我不明白如何在迭代时修改集合。我在方法开始时将所有内容复制到局部变量。
public void Flush() {
var tempEntities = attachedEntities.Select(item => item).ToList();
attachedEntities.Clear();
var tempEntitiesToDelete = entitiesToDelete.Select(item => item).ToList();
entitiesToDelete.Clear();
foreach (var attachedEntity in tempEntities) {
var isTransient = (bool)GetPrivateField(attachedEntity.GetType(), attachedEntity, "isTransient");
if (isTransient)
db.Insert(attachedEntity);
else
db.Update(attachedEntity);
}
foreach (var entity in tempEntitiesToDelete)
db.Delete(entity);
}
堆栈跟踪
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.Collections.Generic.List`1 Enumerator[Compass.Mobile.Core.DataAccess.IEntity].VerifyState () [0x00000] in <filename unknown>:0
at System.Collections.Generic.List`1 Enumerator[Compass.Mobile.Core.DataAccess.IEntity].MoveNext () [0x00000] in <filename unknown>:0
at System.Linq.Enumerable <CreateSelectIterator>c__Iterator1D`2[Compass.Mobile.Core.DataAccess.IEntity,Compass.Mobile.Core.DataAccess.IEntity].MoveNext () [0x00000] in <filename unknown>:0
at System.Collections.Generic.List`1[Compass.Mobile.Core.DataAccess.IEntity].AddEnumerable (IEnumerable`1 enumerable) [0x00000] in <filename unknown>:0
at System.Collections.Generic.List`1[Compass.Mobile.Core.DataAccess.IEntity]..ctor (IEnumerable`1 collection) [0x00000] in <filename unknown>:0
at System.Linq.Enumerable.ToList[TSource] (IEnumerable`1 source) [0x00000] in <filename unknown>:0
at Compass.Mobile.Core.DataAccess.Session.Flush () [0x00000] in <filename unknown>:0
at Compass.Mobile.Core.DataAccess.Session.Commit () [0x00000] in <filename unknown>:0
at Compass.Mobile.Core.Bootstrap.CommandBus.Flush () [0x00000] in <filename unknown>:0