Entity Framework Core support for SQL Spatial Data Types - DBGeography?

此生再无相见时 提交于 2019-12-23 09:35:28

问题


I want to make a web application using ASP.NET Core Razor Pages that has some geographic data in SQL Server. Visual Studio gives an error that it doesn't support the Geography data type when creating the EF model using EF Core from an existing SQL DB. Is there a way to use SQL Spatial Data Types like Geography in an ASP.NET Core project using Entity Framework or EF Core?

This link shows some workarounds but nothing out of the box.

This link is an older post dealing with this question.


回答1:


Spatial data support is introduced with the version 2.2 of Entity Framework Core. It uses NetTopologySuite data types and maps them to geography or geometry SQL Server types. You can install NetTopologySuite via NuGet:

Install-Package NetTopologySuite

And you will also need the following NuGet package for EF Core spatial data support for SQL Server:

Install-Package Microsoft.EntityFrameworkCore.SqlServer.NetTopologySuite

and to use the UseNetTopologySuite option in your EF context configuration:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer(
        @"my connection string",
        x => x.UseNetTopologySuite());
}

Then you can do something like this:

var nearestCity = db.Cities
    .OrderBy(c => c.Location.Distance(currentLocation))
    .FirstOrDefault();

I wrote about it in my Finding Nearby Users with Entity Framework Core Spatial Data blog post.




回答2:


I just stumbled across your post and also the first link you mentioned. Only a few days ago, a preview version of EntityFrameworkCore 2.2.0 was published which is supposed to support spatial data types in SQL Server.

See https://github.com/aspnet/EntityFrameworkCore/issues/1100#issuecomment-417618315 and the following comments.

I haven't tried it myself yet and it's probably not working 100%, but it's surely worth a try.



来源:https://stackoverflow.com/questions/51681889/entity-framework-core-support-for-sql-spatial-data-types-dbgeography

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!