Spatial Data with Entity Framework Core

At the time of writing this blog, Microsoft has launched version 2.2.0-preview2 for Entity Framework Core. Entity Framework version 2.2.0-preview2 has started support for SQL Spatial data type. which was really a missing piece in Entity Framework Core. I will show you how to use Entity Framework Core with Spatial Data.

Let’s Get our Understanding Clear for Spatial Types

What is Spatial Data?

Information about the locations and shapes of geographic features. and the relationships between them, usually stored as coordinates and topology.

What makes Spatial Data?

Spatial data consists of geometry types and geographical types.

The geometry data type supports planar, or Euclidean (flat-earth), data.

The geography data type, which supports ellipsoidal (round-earth) data. Such as GPS latitude and longitude coordinates.

Simple Types:
  • Point
  • LineString
  • CircularString
  • CompoundCurve
  • Polygon
  • CurvePolygon
Collection Types:
  • MultiPoint
  • MultiLineString
  • MultiPolygon
  • GeometryCollection

Add Nuget Package

Before getting started we need to add this Microsoft.EntityFrameworkCore.SqlServer.NetTopologySuite Nuget package.

Create an Entity with Spatial Data

Let’s start with creating a simple Entity class to store Point Data in Database.

When we run this against SQL server, we will get a Geography field for the Location property.

Creating Database Context Factory Class

We need to enable NetTopologySuite in DbContext. we need to call the UseNetTopologySuite() method inside UseSqlServer(). Either in OnConfiguring() or AddDbContext(). If you want to use DbContextFactory pattern you can read this post.


Adding Spatial Data to the Database

So, Let’s add some data to the database table which includes some latitude and longitude data with this data we can query using LINQ.

To Add the Actual Geometry Data, we need to create an instance of NetTopologySuite.Geometries.Point Type to create a new Point and assign it to Location Property.

This what it looks like in the database.

Point data in the database.

Query Spatial Data

Now, we have some Location data in the database and it is really easy to query the data and find the distance between the locations (aerial distance).

In this query, we look for a number of locations that are near a fixed Point. So, Query for Latitude and Longitude of Chandigarh City. Let’s try to find cities which are within 300 KM range (aerial distance).



This feature is still in preview and it will be available in the next release of EntityFramework Core.


Fork it on Github and don’t forget to star it.

Other Posts you might like

Leave a Reply

Your email address will not be published. Required fields are marked *