我的实体框架数据库上下文具有以下内容:
public DbSet<TableCell> TableCells { get; set; }
表单元格业务逻辑类具有用于添加以下功能:
public void addTableCell(TableCell tc)
{
context.TableCells.Add(tc);
context.SaveChanges();
}
单元格实体是这样的:
[Table("TableCell")]
public class TableCell
{
public TableCell()
{
this.TableElements = new HashSet<TableElement>();
this.SomeObjects = new HashSet<SomeObject>();
}
[Key]
public int PK_TableCellID { get; set; }
[Required]
public int Row { get; set; }
[Required]
public int Column { get; set; }
[Required]
[ForeignKey("Table")]
public int FK_TableID { get; set; }
public ICollection<TableElement> TableElements { get; set; }
public ICollection<SomeObject> SomeObjects { get; set; }
public Table Table{ get; set; }
}
我想创建一个表,用户将选择表的大小,并为用户创建单元格。每个单元将包含一些元素。为此,我有一个像这样的方法:
public void createTableWithCells()
{
Table table = new Table
{
//row number added here with the user input
//column number added here with the user input
//I don't add any cell object here.
};
TableLogic.addTable(table);
for (int row = 0; row < table.rowNumber; row++)
{
for (int column = 0; column < table.columnNumber; column++)
{
TableCell cell = new TableCell
{
//cell elements, properties etc.
SomeObjects = someObjectList,
Table = table
};
cellLogic.addTableCell(cell);
}
}
}
问题是,for循环仅添加一个单元格。第一次迭代后,在第二次迭代中,出现在行中
cellLogic.addTableCell(cell);
我在cellLogic的add方法上遇到了异常。在这里:
context.TableCells.Add(tc);
该异常表示:“集合已修改;枚举操作可能无法执行。”
答案 0 :(得分:0)
感谢@JaredPar在Collection was modified; enumeration operation may not execute中的回答,我已经解决了问题
我更改了以下代码:
TableCell cell = new TableCell
{
//cell elements, properties etc.
SomeObjects = someObjectList,
Table = table
};
到
TableCell cell = new TableCell
{
//cell elements, properties etc.
SomeObjects = someObjectList.toList(),
Table = table
};