首页 > 解决方案 > 使用实体框架获取视图数据非常慢

问题描述

我正在开发一个 ASP.NET MVC 4 应用程序,在该应用程序中我试图创建一个从 2 个数据库视图读取的仪表板;一种视图列出了具有计数和目标的建筑物,另一种视图列出了具有计数和目标的建筑物的楼层。我正在尝试将它们组合在仪表板上,因此我创建了一个名为的数据模型,该模型DashboardView将建筑物与物业的楼层保持在一起Children

它在本地运行良好,但部署在生产 IIS 服务器上运行速度非常慢,我不确定这是否是由于我访问数据的方式效率低下:

using (var db = new MyDBContext())
{
    var views = (from building in db.BuildingViews.OrderBy(x => x.BuildingName) select new { building })
                .AsEnumerable()
                .Select(bldgView => new DashboardView
                {
                    ViewType = "Building",
                    ViewLabel = bldgView.building.BuildingName,
                    CurrentCount = bldgView.building.Count,
                    GoalCount = bldgView.building.Goal,
                    Children = (from floors in db.FloorViews.Where(v => v.BuildingId == bldgView.Building.BuildingId) select new { floor })
                                .AsEnumerable()
                                .Select(floorView => new DashboardView
                                {
                                    ViewType = "Floor",
                                    ViewLabel = floorView.floor.FloorName
                                    CurrentCount = floorView.floor.Count,
                                    GoalCount = floorView.floor.Goal
                                }).ToList()
                }).ToList();

    double totalBldgCount = db.BuildingViews.Select(x => x.Count).Sum();
    double totalGoalCount = db.BuildingViews.Select(x => x.Goal).Sum();
}

有没有更好的方法来创建我想要在这里实现的数据包,或者这个问题可能与多人同时访问数据库有关?

::编辑::

我现在明白 using.AsEnumerable()可能是性能不佳的罪魁祸首;但是我很难理解如何在没有它的情况下正确构建我DashboardView的子DashboardView对象,因为这不起作用:

var query = (from buildings in db.BuildingViews
            join floors in db.FloorViews on buildings.BuildingId equals floors.BuildingId
            select new DashboardSprinklerView
            {
                ViewType = "Building",
                ViewLabel = building.BuildingName,
                CurrentCount = building.Count,
                GoalCount = building.Goal,
                Children = (floor from floors select new DashboardSprinklerView
                {
                    ....
                }).ToList()
            }).ToList();

标签: c#entity-framework

解决方案


推荐阅读