【问题标题】:Adding second data to context list causes exception将第二个数据添加到上下文列表会导致异常
【发布时间】:2019-04-04 02:24:09
【问题描述】:

我的实体框架数据库上下文有这个:

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

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

【问题讨论】:

  • 代码不足以提供任何帮助。您的方法 createTableWithCells 创建了一个新的 Table 对象,没有设置任何属性,然后以相同的方法循环遍历该表的列。不确定您是如何获得该列的列表的!请遵循本指南为任何人提供足够的代码来帮助您。 stackoverflow.com/help/mcve
  • 我是用注释行写的。 “//定义表格属性,但我不在这里添加任何单元格对象。”当然这不是真正的代码,因为真正的代码是一团糟,没有必要把所有的东西都放在这里。它可能会混淆人们。这就是我写 //defining table properties 的原因,这意味着我在那里定义了必要的属性,但我没有向你展示所有这些属性。抱歉,不清楚。让我编辑。
  • 加入这个聊天,我们可以在那里讨论。 chat.stackexchange.com/rooms/85141/question-discussion
  • 我必须在 Stack Exchange Network 上拥有 20 名声望才能在那里交谈。我是新用户。对不起。
  • 你试过那个链接了吗?我给了你访问权限..

标签: c# entity-framework business-logic


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 2011-07-22
    • 2022-01-23
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多