使用Entity Framework删除db中的项目失败

时间:2016-09-27 18:11:54

标签: c# database entity-framework asp.net-mvc-4 entity-framework-6

我在数据库中有一个名为Course_Predecessor的表,我正在尝试使用EF删除此表中的所有项目,然后向表中添加新数据。 我无法删除数据,因为我收到以下错误:“集合被修改枚举操作可能无法执行”

这是我正在使用的代码(在一个函数内部,它接收db的上下文作为ctx)

List<Course_Predecessor> lst = new List<Course_Predecessor>();
fillTheList(ref lst , someData);

ctx.Course_Predecessor.RemoveRange(ctx.Course_Predecessor.ToList());
ctx.Course_Predecessor.AddRange(predecessors);

我在RemoveRange函数中得到了错误。

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

<?import java.net.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.canvas.*?>

<HBox fx:id="container" id="container" fx:controller="core.GuiController" xmlns:fx="http://javafx.com/fxml">
    <HBox fx:id="post" id="post">
        <!-- Stuff -->
    </HBox>

    <HBox fx:id="friends" id="friends">
        <!-- Stuff -->
    </HBox>

    <HBox fx:id="profile" id="profile">
        <!-- Stuff -->
    </HBox>
</HBox>

答案 1 :(得分:1)

如果您使用的是EF6(看起来很像),那么您应该能够通过执行以下操作删除表中的所有记录。 (请注意.ToList()调用中缺少RemoveRange方法)

ctx.Course_Predecessor.RemoveRange(ctx.Course_Predecessor);
ctx.SaveChanges();

或者你可以这样做:

foreach (var predecessor in ctx.Course_Predecessor)
{
    ctx.Entry(predecessor).State = EntryState.Deleted;
}
ctx.SaveChanges();

两段代码完全相同。

答案 2 :(得分:0)

试试这个,

 ctx.Course_Predecessor.ToList().ForEach(r => ctx.Course_Predecessor.DeleteObject(r));
 ctx.SaveChanges();