使用Entity Framework获取视图数据非常慢

时间:2018-10-09 19:40:40

标签: c# entity-framework

我正在开发一个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();
}

是否有更好的方法来创建我要在此处实现的数据包,还是该问题可能与多个人同时访问数据库有关?

:: EDIT ::

我现在了解到,使用.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();

0 个答案:

没有答案