3

我在我的应用程序中为代码优先实体添加了一个简单的方法,该方法TopicCount接受一个布尔值。它计算导航属性中的项目数,并根据传入的布尔值是 true 还是 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();
    }
}

当我调用此TopicCount方法时,它会失败(无论布尔值是真还是假),并出现以下错误:

已经有一个与此命令关联的打开的 DataReader,必须先关闭它。

有任何想法吗?

4

2 回答 2

4

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.

于 2012-09-20T21:18:59.567 回答
3

我认为最快的我解决了我自己的问题。原来我正在迭代一个延迟加载的Board实体集合。在该迭代中,我随后迭代了 Board 的导航属性,它是另一个数据读取器。

The simple fix was to call .ToList() on the collection of boards and iterate over the in-memory collection.

于 2012-09-20T18:36:55.707 回答