LINQ to Entity不支持DbGeography条件

时间:2015-09-06 20:22:57

标签: c# entity-framework-6 geospatial spatial-query

我使用的是.NET 4.5和EF 6.0(也尝试过使用6.1.3)。 我在实体表( System.Data.Entity.Spatial.DbGeography )中有Location geography 列。

using System.Data.Spatial; //also tried Entity one

public class Entity
{
    public DbGeography Location {get;set;}
}

在LINQ中,我试图选择指定区域内的所有实体。

var center = DbGeography.FromText(string.Format("POINT({0} {1})", latitude, longitude), 4326);
var region = center.Buffer(radius);
var result = db.Entities.Where(x => SqlSpatialFunctions.Filter(x.Location, region) == true).ToArray();

此查询返回错误:

An unhandled exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll

Additional information: The specified type member 'Location' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

如果是这样的话:

http://referencesource.microsoft.com/#System.Data.Entity/System/Data/Objects/SqlClient/SqlSpatialFunctions.cs

这是如何在网络上的示例中发挥作用的?

UPD。使用Intersects()

时出现同样的问题
var center = DbGeography.FromText(string.Format("POINT({0} {1})", latitude, longitude), 4326);
var region = center.Buffer(radius);
var result = db.Entities.Where(x => x.Location.Intersects(region) == true).ToArray();

3 个答案:

答案 0 :(得分:0)

如果不是使用STIntersects()或STWithin()或其等效的EF等等,你很可能会得到相同的效果;

// SQL STIntersects() equivalent    
var result = db.Entities.Where(x => x.Intersects(region)).ToArray();

// SQL STWithin() equivalent    
var result = db.Entities.Where(x => x.Intersects(region) == true && x.Difference(region).IsEmpty == true).ToArray();

使用' Intersects'如果您想要所有完全或部分位于该地区的地点。使用'在'内如果您只想要那些完全在该地区内的人。

答案 1 :(得分:0)

如果您使用的是DB First方法,则需要从模型浏览器更新模型,但不能手动更新。

答案 2 :(得分:0)

在我的情况下,我的Linq查询不允许我使用:

x.Intersects(region) == true

我必须将此更改为

x.Intersects(region).IsTrue