Search code examples
c#entity-frameworkbusiness-logic

Adding second data to context list causes exception


My entity framework DB context has this:

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

Table cell business logic class has this function for adding:

public void addTableCell(TableCell tc)
{
    context.TableCells.Add(tc);
    context.SaveChanges();
}

Cell entity is this:

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

I want to create a table, user will select the table size and I will create cells for users decision. Every cell will contain some elements. To do this, I have a method like this:

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

The problem is, for loops adds only one cell. After the first iteration, in second iteration when it comes to the line

cellLogic.addTableCell(cell);

I got an exception on cellLogic's add method. Here:

context.TableCells.Add(tc);

The exception says, “Collection was modified; enumeration operation may not execute.”


Solution

  • I have solved the problem thanks to @JaredPar 's answer in Collection was modified; enumeration operation may not execute

    I have changed the following code:

    TableCell cell = new TableCell
    {
        //cell elements, properties etc.
        SomeObjects = someObjectList,
        Table = table
    };
    

    to

    TableCell cell = new TableCell
    {
        //cell elements, properties etc.
        SomeObjects = someObjectList.toList(),
        Table = table
    };