计算MVC中Child中的记录数

时间:2015-09-17 13:29:11

标签: c# asp.net-mvc entity-framework foreign-keys tolist

我希望在MVC中获得与以下问题相同的结果。

    public ActionResult Index()

    {
        //List<Systems> systems;
        //var query = db.SystemFamily.Select(c => c.SystemFamilyID).ToList();
        //foreach (var sid in query)
        //{
        //    systems = db.Systems.Select(c => c.SystemFamilyID == sid).ToList();
        //}
        //int count = systems.Count();//Here you will  get count

        //ViewBag.Counts = count; 
        var viewmodel = new Sys_SysFam();
        foreach (var item in db.SystemFamily)
        {
            int id = item.SystemFamilyID;

            //SystemsCount 
            int count = db.Systems.Where(x => x.SystemFamilyID == id).Count();   // Here while debugging it has the value for id but throws exception. 
            item.SystemsCount = count;
        }
        ViewBag.Count = db.SystemFamily.Where(x=>x.deleteFlag==false).Count();   //All these work
        int count1 =db.Systems.Count();    // I even tried it with a where condition passing a SystemFamilyID. Even that worked
        ViewBag.SCount = count1;
        return View(db.SystemFamily.Where(x=>x.deleteFlag==false).ToList());
    }

我得到例外

类型&#39; System.Data.Entity.Core.EntityCommandExecutionException&#39;的例外情况发生在EntityFramework.SqlServer.dll中但未在用户代码中处理

附加信息:执行命令定义时发生错误。有关详细信息,请参阅内部异常 这是内在的例外 已经有一个与此命令关联的打开DataReader,必须先关闭它。

this is the result that needs to be achieved

1 个答案:

答案 0 :(得分:5)

您获得的异常基本上是您在迭代另一个查询的结果时执行查询。

在代码中

尝试使用foreach语句

      foreach (var item in db.SystemFamily.ToList())
      {
        int id = item.SystemFamilyID;

        //SystemsCount 
        int count = db.Systems.Where(x => x.SystemFamilyID == id).Count();   
        item.SystemsCount = count;
     }

或者您可以在连接字符串中添加MARS将 MultipleActiveResultSets = true 添加到连接字符串的提供者部分(指定数据源,初始目录等)。

相关问题