Reputation: 59234
I added a simple method to a code-first entity in my application called TopicCount
which accepts a boolean. It counts the number of items in a navigation property and the count filters differently based on if the passed in boolean is true or false.
public class Board
{
public short BoardID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool Hidden { get; set; }
public bool ModsOnly { get; set; }
public bool Locked { get; set; }
public bool Anonymous { get; set; }
public bool AllTopics { get; set; }
public virtual ICollection<Topic> Topics { get; set; }
public long TopicCount(bool isModerator)
{
if (isModerator)
return this.Topics.ToList().Count;
else
return this.Topics
.Where(x => !x.ModsOnly)
.Where(x => !x.Board.ModsOnly)
.Where(x => !x.Board.Hidden)
.Count();
}
}
When I call this TopicCount
method it fails (whether the bool is true or false) with the following error:
There is already an open DataReader associated with this Command which must be closed first.
Any ideas?
Upvotes: 3
Views: 550
Reputation: 4622
This is also a symptom of streaming the results of multiple commands on a single context (ala lazy loading). You can set “MultipleActiveResultSets=True" in your connection string to get around that.
Upvotes: 4
Reputation: 59234
Fastest I've ever solved a question of my own I think. Turns out I was iterating over a lazy-loaded collection of Board
entities. Within that iteration I was then iterating over a navigation property of Board, which is another data reader.
The simple fix was to call .ToList()
on the collection of boards and iterate over the in-memory collection.
Upvotes: 3