【问题标题】:Is there a way to use SqlSpatialFunctions without Linq to Entities?有没有办法在没有 Linq to Entities 的情况下使用 SqlSpatialFunctions?
【发布时间】:2015-01-28 12:23:51
【问题描述】:

来自System.Data.Entity.SqlServer.SqlSpatialFunctions类定义:

包含将 Linq 中的 SqlServer 方法公开给实体的函数存根。

我知道特别提到了 Linq to Entities,但是我想知道是否可以在我的后端代码中复制某些功能。

我有一个帐户模型,带有延迟加载的多边形集合。每个多边形都包含一个名为 Location 的 DbGeography 类型属性。

我正在尝试获取与某个点相交的所有多边形(它还具有延迟加载的属性地址,它具有称为位置的 DbGeography 类型属性)。

我可以这样做:

var matchedPolygons =
    account.Polygons.Where(
       x =>
          point.Address.Location.Intersects(x.Polygon.Location)).ToList();

效果很好。

为了尝试提高性能,我认为稍微减少 Polygon 数据是个好主意。

var matchedPolygons =
    account.Polygons.Where(
       x =>
          point.Address.Location.Intersects(SqlSpatialFunctions.Reduce(x.Polygon.Location, 100))).ToList();

然而,这会引发以下 System.NotSupportedException 异常:

此函数只能从 LINQ to Entities 调用。

我知道我可以使用上面的 Reduce 方法直接从我的存储库层检索多边形,但由于我使用延迟加载并且已经有 Polygons 集合可供我使用,我认为可能有一种使用方法 SqlSpatialFunctions 在这个阶段。

【问题讨论】:

    标签: c# sql-server linq linq-to-entities spatial


    【解决方案1】:

    我唯一能想出一个粗略的破解方法。它有效,但我不主张优雅。

    折腾这些包括(也做参考):

    using System.Data.Entity.Spatial;
    using System.Data.SqlTypes;
    

    将 DbGeography 转换为 SqlGeography:

        Microsoft.SqlServer.Types.SqlGeography sqlGeography = Microsoft.SqlServer.Types.SqlGeography.STGeomFromWKB(new SqlBytes(geog.AsBinary()), mydbgeog.CoordinateSystemId);
    

    如果你把它保留为 SqlGeography 可能没关系,但如果不将它转换回来。

    sqlGeography = sqlGeography.Reduce(50);
    
    mydbgeog = DbGeography.FromBinary(sqlGeography.STAsBinary().Value);
    

    It's the fastest way I know of to toss back and forth between DbGeography and SqlGeography。同样,它很粗糙,需要额外的库,但老实说,SqlGeography 中有很多东西对于大型 GIS 应用程序可能需要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-01
      • 1970-01-01
      • 2016-01-10
      • 2016-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多