将第二个数据添加到上下文列表会导致异常

Adding second data to context list causes exception

我的 entity framework 数据库上下文有这个:

public DbSet<TableCell> TableCells { get; set; }

Table 单元格业务逻辑 class 有这个函数可以添加:

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; }
}

我想创建一个 table,用户将 select 大小设为 table,而我将创建单元格供用户决定。每个单元格都会包含一些元素。为此,我有一个这样的方法:

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 的添加方法上遇到异常。这里:

context.TableCells.Add(tc);

异常显示,“集合已修改;枚举操作可能无法执行。”

感谢@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
};