Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
770 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...