Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 在一个函数中对单个模型运行多个linq查询_Asp.net_Linq_Model - Fatal编程技术网

Asp.net 在一个函数中对单个模型运行多个linq查询

Asp.net 在一个函数中对单个模型运行多个linq查询,asp.net,linq,model,Asp.net,Linq,Model,因此,作为学校项目的一部分,我正在尝试建立一个简单的论坛。我找不到任何与我的风格很好的结合,那里是免费的,所以我自己做基本的 使用列表,我将输出表单,然后线程,然后帖子,这样它将深入3页 我遇到的问题是在第一页上,我想从数据库中获取帖子/线程的当前计数。由于这可能会改变在一个时刻注意,我想我会计算页面负载,因为这个项目最多可能有100条记录计数从 下面的代码抛出错误 public ActionResult Index(int page = 1) { Vie

因此,作为学校项目的一部分,我正在尝试建立一个简单的论坛。我找不到任何与我的风格很好的结合,那里是免费的,所以我自己做基本的

使用列表,我将输出表单,然后线程,然后帖子,这样它将深入3页

我遇到的问题是在第一页上,我想从数据库中获取帖子/线程的当前计数。由于这可能会改变在一个时刻注意,我想我会计算页面负载,因为这个项目最多可能有100条记录计数从

下面的代码抛出错误

        public ActionResult Index(int page = 1)
    {
        ViewBag.Title = "Forums";
        var model = db.forums.OrderBy(x=> x.forumID).ToPagedList(page, 15);
        foreach (var m in db.forums)
        {
            m.postCount = db.threads.Where(t => t.forumID == m.forumID && t.threadID == t.parentThreadID ).Count();
            m.threadCount = db.threads.Where(t => t.forumID == m.forumID).Count();
        }
        return View(model);
    }
抛出错误

Exception Details: System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.

Source Error: 



Line 20:             foreach (var m in db.forums)
Line 21:             {
Line 22:                 m.postCount = db.threads.Where(t =>  t.forumID == m.forumID && t.threadID == t.parentThreadID ).Count();
Line 23:                 m.threadCount = db.threads.Where(t => t.forumID == m.forumID).Count();
Line 24:             }

原来我在db.forums中循环,需要循环我的模型,因为我已经检索到了详细信息

 foreach (var m in model)
    {
        m.postCount = db.threads.Where(t => t.forumID == m.forumID && t.threadID == t.parentThreadID ).Count();
        m.threadCount = db.threads.Where(t => t.forumID == m.forumID).Count();
    }

我建议只对模型进行一次调用,然后使用Linq对其进行两次过滤

示例代码:

foreach (var m in model)
{
    var threads = db.threads.ToList();
    m.postCount = threads.Where(t =>  t.forumID == m.forumID && t.threadID == t.parentThreadID).Count();
    m.threadCount = threads.Where(t => t.forumID == m.forumID).Count();
}