【问题标题】:Will eager loading a Linq to Entity query before rendering my view slow things down?在呈现我的视图之前急切加载 Linq to Entity 查询会减慢速度吗?
【发布时间】:2015-08-08 22:45:45
【问题描述】:

当我的视图被渲染时,我需要从我的视图模型中获取位置数据(长/纬度坐标数组)。我将使用 Javascript 读取这些值并将它们绘制在 Google 地图中。目前我正在获取包含位置数据的结果,但我不确定如何有效地从结果中获取位置数据并将它们放入我的视图模型中的另一个属性中。这应该是急切加载,延迟加载等吗?我是 Linq 和 EF 的新手。

我有一个看起来像这样的视图模型

public class YogaSpaceListViewModel
{
    public IPagedList<YogaSpaceResults> YogaSpaces { get; set; }
    // I need to put all LocationPoints data from the query results into a collection here
    //public some collection here LocationResults { get; set; }
}

仅供参考,IPagedList 继承自 IEnumerable。

当我在这里获取结果时是我的查询。我将结果放入匿名类型“YogaSpaceResults”中,您可以看到它包含我想要存储在视图模型中的“LocationPoints”数据。

var events = (from u in context.YogaSpaceEvents
    orderby u.YogaSpace.Address.LocationPoints.Distance(myLocation)
    where
        (u.DateTimeScheduled >= classDate) &&
        (u.YogaSpace.Address.LocationPoints.Distance(myLocation) <= 8047)
            select new YogaSpaceResults 
            {   
                LocationPoints = u.YogaSpace.Address.LocationPoints,
                Title = u.YogaSpace.Overview.Title,
                Summary = u.YogaSpace.Overview.Summary,
                Date = u.DateTimeScheduled
            }).ToPagedList(page, 10);

在我看来,我正在做这样的事情

@foreach (var space in Model.YogaSpaces)
    {
        <div>
            <h4>@space.Title</h4>
            <div>
                @space.Summary
                <br/>
                @space.Date
            </div>
        </div>
        <hr />
    }

【问题讨论】:

    标签: asp.net-mvc linq entity-framework linq-to-entities


    【解决方案1】:

    我不确定如何有效地从结果中获取位置数据并将它们放入我的视图模型中的另一个属性中。这应该是热加载、延迟加载等吗?

    当你执行 ToPagedList 时,它们已经从数据库中加载了,所以你不需要加载它们,一切都会在内存中完成

    你可以有一些非常简单的东西,比如

    public IEnumerable<LocationPoint> LocationResults {
        get{
            return YogaSpaces.Select(ys => ys.LocationPoints)
        }
    }
    

    顺便说一句,您似乎已经以一种有效的方式从数据库中获取数据(您使用单个查询在视图模型中投影所需的属性,这比延迟加载或急切加载更有效)所以您可以轻松保留您当前的代码。

    注意,如果你发现你的查询速度太慢,可能是因为这种情况缺少空间索引

    (u.YogaSpace.Address.LocationPoints.Distance(myLocation) <= 8047)
    

    【讨论】:

      猜你喜欢
      • 2016-12-01
      • 2017-12-24
      • 1970-01-01
      • 1970-01-01
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-06
      相关资源
      最近更新 更多