【问题标题】:Spatial type Entity Framework Core SQL Server空间类型 Entity Framework Core SQL Server
【发布时间】:2017-10-19 15:59:17
【问题描述】:

我需要处理地理距离。

我明白了

public class Clinic
{
    ...
    public double Latitude
    public double Longitud
    ...
}

此诊所位于 SQL Server 数据库中。我需要将它们按距离排序返回到某个点。 对于我阅读的内容,Entity Framework Core 不支持 DbGeography 或类似的东西来表示 SQL Server 类型:

geography

我在数据库中添加了一列,其中包含每个诊所的计算地理点

UPDATE Clinics SET Geo = geography::Point(Clinics.Latitude, Clinics.Longitud,4326)

好的,知道我需要按订单退回。 SQL 通过查询支持这一点

DECLARE @p geography;
SET @p = geography::Point(41,2,4326);
SELECT * FROM Clinics c ORDER BY @p.STDistance(c.Geo);

Entity Framework Core 支持使用原始 SQL 进行查询。

context.Clinics.FromSql("..query..")

正如 FromSql 的文档所说,如果您返回的数据与模型不完全匹配,它就会崩溃。 与在 C# 中一样,我无法拥有代表 Geo 的 DbGeography,我无法弄清楚如何解决这个问题。

编辑 1:

让它部分使用以下内容:

string rawSQL = @"
        DECLARE @p geography;
        SET @p = geography::Point(41,2,4326);
        SELECT c.Id, c.Name, c.Price, c.Quote, c.QuoteAuthor, c.QuoteSource, c.Description, c.Image, c.Latitude, c.Longitude, c.Category, c.CenterDistance, c.NumReviews, c.Stars
        FROM Clinics c
        ORDER BY @p.STDistance(c.Geo); ";
query = query.FromSql(rawSQL);

所以现在我获得了诊所的所有属性并且它可以工作了!问题是,诊所有一个相关的类设施

public class Clinic
{
    ...
    public double Latitude
    public double Longitud
    public Amenity amenity
    ...
}

因此,当我运行查询时,我需要通过 linq 包含便利设施

query = query.Include(c => c.ClinicAmenities).ThenInclude(ca => ca.Amenity);

死了,因为我相信原始 sql 中的 Orderby 出现在 include 之前

【问题讨论】:

  • 你发现了吗?您在“ThenIncluded”Amenity 时是否收到错误消息?

标签: c# sql-server entity-framework entity-framework-core


【解决方案1】:

你没有说明你得到了什么错误。

在我看来,您收到错误“调用存储过程时不支持包含操作。”

你可以做的是执行两个查询。

类似的东西

dbContext.Amenities.Load();

string rawSQL = @"
          DECLARE @p geography;
          SET @p = geography::Point(41,2,4326);
          SELECT c.Id, c.Name, c.Price, c.Quote, c.QuoteAuthor
          FROM Clinics c
          ORDER BY @p.STDistance(c.Geo)";

// EF will automatically wire up the references between entities 
// that have been queried for
var clinicsWithAmenities = dbContext.Clinics.FromSql(rawSQL).ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 1970-01-01
    • 2017-12-27
    • 2022-08-02
    • 2020-09-10
    • 2018-04-12
    • 1970-01-01
    相关资源
    最近更新 更多