c# - 另一个 "There is already an open DataReader associated......"

标签 c# .net entity-framework postgresql

有什么提示可以关闭DataReader吗?我使用 postgresql,而 MARS 仅适用于 SQL。或者也许我不需要 MARS 解决这个我不知道的问题。错误显示在 foreach 循环中。感谢您的提示。

var months = (from month in connector.PositionInstance where month.FeeNoticeMonth >= DateTime.Now.Month select month);

foreach (PositionInstance p in months)
{
    System.Windows.MessageBox.Show("" + p.First().Position.Name);
}

编辑: 我有两个表 PositionInstance 和 Position:

CREATE TABLE "Position"
(
"PositionId" integer NOT NULL DEFAULT,
"Name" character varying(30) NOT NULL,
CONSTRAINT "PK_Position" PRIMARY KEY ("PositionId")
)

CREATE TABLE "PositionInstance"
(
"PositionInstanceId" integer NOT NULL DEFAULT,
"FeeNoticeYear" integer NOT NULL,
"FeeNoticeMonth" integer NOT NULL,
CONSTRAINT "PK_PositionInstance" PRIMARY KEY ("PositionInstanceId"),
CONSTRAINT "FK_Position_PositionInstance" FOREIGN KEY ("PositionId")
REFERENCES "Position" ("PositionId") MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION 
)

最佳答案

由于延迟加载,您的情况可能会出现此问题,延迟加载发生在 foreach 循环内部。它试图在循环的每次迭代中从数据库加载每个 Position

解决此问题的一种方法是使用预先加载在您的查询中一次获取所有 Positions。然后,如果您还在查询末尾使用贪婪操作(例如 ToList()),则会执行 DB 并一次拉取所有内容。在你的情况下尝试像

var months = 
    (from month in connector.PositionInstance 
     where month.FeeNoticeMonth >= DateTime.Now.Month 
     select month).Include("Position").ToList();

或一些变化。在查询之后使用 ToList() 会将变量 months 键入为 List(这是一个 IEnumerable)包含来自数据库的填充结果;否则 months 将是一个尚未执行数据库查询的 IQueryable

关于c# - 另一个 "There is already an open DataReader associated......",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15926632/

相关文章:

.net - 迭代 Queue<T> 是否保证按队列顺序?

C# 对象池与 Interlocked.Increment

c# - 如何在AutoMapper的MapperConfiguration中使用mapper.Map?

c# - 动态创建 UI 和数据库,最好的方法是什么?

entity-framework - 与 Entity Framework 代码一起使用的设计模式

c# - ISerializable 和继承,正确使用,CA2236

C# 反序列化 JSON html 字符串

c# - 使用反射更改方法访问修饰符

c# - wpf中的多列自动搜索用户控件

c# - 同一数据库中的两个 IdentityDbContext