c# - 空间类型 Entity Framework Core SQL Server

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

我需要处理地理距离。

我得到了

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);

所以现在我得到了诊所的所有属性并且它起作用了!问题是,诊所有一个相关的类 Amenities

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 在包含之前出现而死了

最佳答案

你没有指定你得到的错误。

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

您可以执行两个查询。

像这样

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();

关于c# - 空间类型 Entity Framework Core SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44071441/

相关文章:

c# - 在 for each 循环中使用 DisplayFor

Linux 上的字符集与 ODBC 到 SQL Server 不匹配

sql - 授予一天中特定时间的权限

entity-framework - Entity Framework 和带有显式链接表的多对多关系

entity-framework - 与 WillCascadeOnDelete 的单向关联

c# - 如何循环遍历数据表中的每一行并在mySQL中插入数据

c# - 从 OleDb 连接字符串获取用户

c# - EF ICollection 与 List 与 IEnumerable 与 IQueryable

c# - 读取鼠标拖动的项目

sql - 如何根据与先前日期相关的条件按日期找出不同的人数?