我有一个名为Pathway的EntityObject,它直接与路径表中的数据相关。我的数据库还存储了Pathway自定义的规则。我想要做的是在我的代码中创建一个Pathway对象,它是Pathway + PathwayCustomisations的结果。结果应该永远不会找到返回数据库的方式,它只是代码中使用的临时投影。
public static Pathway ApplyCustomisation(Pathway p, ICollection<PathwayCustomisation> c)
{
Pathway resultant = new Pathway();
if (!p.PathwayModule.IsLoaded) p.PathwayModule.Load();
foreach (PathwayModule m in p.PathwayModule)
{
resultant.PathwayModule.Add(m);
}
foreach (PathwayCustomisation i in c)
{
switch (i.Command)
{
case "ADD":
resultant.PathwayModule.Add(i.PathwayModule);
break;
case "DELETE":
resultant.PathwayModule.Remove(i.PathwayModule);
break;
}
}
return resultant;
}
这个方法在第一个障碍时窒息,因为我将PathwayModule实体添加到第二个Pathway,因为它们只能属于模型/数据库中的一个:
CoursePlanner.Test.PathwayTest.ApplyCustomisation:
System.InvalidOperationException : Collection was modified; enumeration operation may not execute.
有没有办法轻松使用实体投影?我是否正确处理了这个问题?
编辑:
只有方法的第一部分才能得到异常:
public static Pathway ApplyCustomisation(Pathway p, ICollection<PathwayCustomisation> c)
{
Pathway resultant = new Pathway();
if (!p.PathwayModule.IsLoaded) p.PathwayModule.Load();
foreach (PathwayModule m in p.PathwayModule)
{
resultant.PathwayModule.Add(m);
}
return resultant;
}
上面的枚举不会修改枚举的同一个集合,只是将项目添加到第二个集合中。此代码提供了相同的异常。
.NET3.5,C#,VS Express 2008
谢谢,
丹尼尔
答案 0 :(得分:2)
您的例外是由于您在枚举时修改了一个集合而引起的。
foreach (Item item in collection)
{
collection.Add(something); // Not allowed.
collection.Remove(something); // Not allowed, too.
}
使用普通对象之类的实体是没有问题的 - 您必须避免将实体附加到对象上下文(直接或间接通过相关实体),并且它们不会持久保存到数据库中。