gpt4 book ai didi

c# - Entity Framework 错误 : There is already an open DataReader associated with this Command

转载 作者:行者123 更新时间:2023-12-05 08:30:04 26 4
gpt4 key购买 nike

我这里的代码有一些问题。我有这种方法可以检查当前是否有任何书籍与某个类别相关联,如果没有 - 您应该可以将其删除。当我检查一个没有书籍的类别和有与之相关的书籍的类别时,这会起作用。

using(var db = new DatabaseContext())
{
foreach (var cat in db.BookCategories.Include("Books").Where(c => c.Id == CategoryId)) {

if(cat.Books.Count != 0)
{
Console.WriteLine("Category cannot be deleted, because there are still books connected to it");
} else
{
Console.WriteLine("Category can be deleted, because there are no books connected to it");
}
}
}

但是当我在 else 语句下添加 attach、remove 和 savechanges 时,我得到了这个错误“System.InvalidOperationException:‘已经有一个与此连接关联的打开的 DataReader,必须先将其关闭。’

db.attach(cat);
db.remove(cat);
db.savechanges();

我需要做什么才能通过此考试?谢谢

最佳答案

在这段代码中只有一个数据库连接,所以当你这样做的时候

foreach (var cat in db.BookCategories.Include("Books").Where(c => c.Id == CategoryId))

它使用连接开始阅读“书籍”。它开始读取它们,然后一次读取一个。

如果您尝试在循环内执行另一个数据库操作,则会收到该错误消息。原因是连接仍在阅读书籍的过程中,或者换句话说,阅读器仍处于打开状态。

如果你这样做:

...... => c.Id == CategoryId).ToList())

然后它强制将所有 Books 读入列表,并关闭阅读器,所以现在您可以对连接执行其他操作。

关于c# - Entity Framework 错误 : There is already an open DataReader associated with this Command,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66690147/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com