Any tips how to close the DataReader
? I use postgresql and MARS is only for SQL. Or maybe I don't need MARS for this problem I don't know. The error shows in the foreach loop. Thank you for your tips.
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);
}
EDIT: i have two tables PositionInstance and 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
)
This problem is probably happening in your case due to lazy loading, which is happening inside of the foreach
loop. It's trying to load each Position
from the DB on each iteration of the loop.
One way around this is to use eager loading to get all the Positions
at once in your query. Then if you also use a greedy operation such as ToList()
at the end of your query, the DB is executed and everything is pulled in one go. In your case try something like
var months =
(from month in connector.PositionInstance
where month.FeeNoticeMonth >= DateTime.Now.Month
select month).Include("Position").ToList();
or some variation. Using use the ToList()
after the query will type variable months
as a List
(which is an IEnumerable
) containing the populated results from the DB; otherwise months
will be an IQueryable
with the DB query not yet executed.
try to add this in the connection string:
MultipleActiveResultSets=True
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.