在批处理模式下使用EF 6.1调用DbGeography距离函数

时间:2015-11-11 13:56:38

标签: c# sql-server entity-framework geospatial geographic-distance

我在实体框架6.1中使用DbGeography类型与SQL Server 2014,我需要找到可能100,000个实体的最近位置,如下所示逐个执行它是否很慢,是否可以使用类似的方法正如我在下面但是一次完成它们?

C#:

<nav class="main-nav">
  <a href="index3.html">Home</a>
  <a</a>
  <a href="contact.html">Contact</a>
  <a href="directory.html">Directory</a>
</nav>

原因我说这是因为在此之前,我使用存储过程做了类似的事情。

在SQL中类似:

public List<GeocodableEntity> LinkToRoadNodes(List<GeocodableEntity> entities)
{
    foreach (var entity in entities)
    {
        var nearestLocation = GetNearestLocation(entity.Latitude, entity.Longitude, DEFAULT_ROAD_NODE_LINK_RADIUS);
        // update entity with values from nearestLocation
    }

    return entities;
}

private GeoLocation GetNearestLocation(float latitude, float longitude, double searchRadius)
{
    var sourcePoint = Helper.CreateDbGeographyPoint(latitude, longitude);
    return Locations.Where(x => x.Point.Distance(sourcePoint) < searchRadius)
        .OrderBy(x => x.Point.Distance(sourcePoint))
        .FirstOrDefault();
}

@CoordinateList是:

ALTER PROCEDURE [dbo].[GetNearestLocationNodesByCoordinates]
    @CoordinateList dbo.CoordinateListWithRefId READONLY
AS
BEGIN
    WITH InputCTE AS
    (
        SELECT RefID, geography::Point(Latitude, Longitude, 4326) AS Point
        FROM @CoordinateList
    )
    SELECT x.RefID, x.NodeId, x.Latitude, x.Longitude, x.LocationTypeId
    FROM (SELECT I.RefID as 'RefID',
                 L.NodeId,               
                 L.Point.Lat as 'Latitude',
                 L.Point.Long as 'Longitude',
                 L.LocationTypeId,
                 ROW_NUMBER() OVER (PARTITION BY I.RefID ORDER BY L.Point.STDistance(I.Point)) AS Ranking
          FROM InputCTE AS I
          JOIN Location AS L
          ON L.Point.STDistance(I.Point) <= 5000) AS x WHERE Ranking = 1
END

如果可能的话,我想在C#代码中执行相同的操作,而无需触及存储过程或键入SQL查询字面值。

并行Foreach:

EntityFramework.dll中出现“System.InvalidOperationException”类型的异常,但未在用户代码中处理 附加信息:创建模型时无法使用上下文。如果在OnModelCreating方法中使用上下文,或者同时由多个线程访问相同的上下文实例,则可能抛出此异常。请注意,DbContext和相关类的实例成员不保证是线程安全的。

0 个答案:

没有答案