Вопрос

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?

Это было полезно?

Решение

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.

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top