地理空间搜索-实体框架核心/ PostgreSQL

时间:2020-05-23 17:40:39

标签: c# postgresql linq asp.net-core entity-framework-core

我有一个存储一些事件位置的表,以及一个使用ef核心映射到它的类:

int main() 
{
    ifstream inf("smallpopulation.dat");
    vector<person> nodes;

    // If we couldn't open the output file stream for reading
    if (!inf) {
        // Print an error and exit
        cerr << "Uh oh, population.dat could not be opened for reading!" << 
        endl;
        return 1;
    }

    // While there's still stuff left to read
    while (inf) {
        string n;
        int a;
        double s;

        inf >> n >> a >> s;
        nodes.emplace_back(n, a, s);
    }

    // Goes through all instances of `nodes`
    for (const person& p : nodes) {
        cout << p << '\n'; // calls the `std::ostream& operator<<` defined above...
    }
    return 0;
}

问题
Location类与Post具有1-1关系。 现在,假设输入的经纬度和半径为 X km ,我希望能够从数据库中获取该半径范围内的所有帖子。即我想执行地理空间查询。

我找到了一个解决方案,但是它涉及执行一些普通的SQL查询,我会不惜一切代价避免这样做。 我将如何使用LINQ执行它?

1 个答案:

答案 0 :(得分:0)

解决方案来自Postgis。它增加了对地理对象的支持,允许在SQL中运行位置查询。它必须安装在数据库端。对于服务器端,必须安装以下library

可以执行地理空间查询的相关方法称为“ .IsWithinDistance”。 纬度,经度必须作为点和半径传递。这将返回指定范围内的所有记录。

示例:

posts = await Context.Posts
        .Include(p => p.Location)                
        .Where(p => p.Location.Location.IsWithinDistance(location, radius * 1000) 
        .AsNoTracking().ToListAsync();