Course contentsShow
← C#
Lesson 1115 of 1,90810. Entity Framework Core ModelingFree lesson

Spatial Data Mapping

Work with geographic and geometric data types in spatial database systems.

In this lesson, you will learn how to map geographic and geometric data types directly into your C# entities using Entity Framework Core.

When working with spatial data, we are moving beyond simple strings or integers to store complex coordinates like latitude/longitude pairs (Point) or map boundaries (Polygon). To handle this, EF Core leverages the NetTopologySuite library, which serves as the bridge between your C# objects and the spatial types supported by SQL Server or PostgreSQL (like GEOGRAPHY or GEOMETRY).

Configuring Spatial Data

First, you must ensure your project includes the provider-specific package, such as Microsoft.EntityFrameworkCore.SqlServer.NetTopologySuite. Once installed, you can simply use spatial types within your entity models.

using NetTopologySuite.Geometries;

public class DeliveryLocation
{
    public int Id { get; set; }
    public string Address { get; set; }
    // Represents a geographic point (e.g., GPS coordinates)
    public Point Location { get; set; } 
}

Mapping and Querying

When EF Core processes this model, it recognizes the Point type and automatically maps it to the database's spatial column. You don't need complex value converters for the basics; the spatial provider handles the translation between the database’s binary spatial format and the NetTopologySuite objects.

The real power appears when querying. Because the provider maps these types correctly, you can perform spatial operations directly in your LINQ queries:

var nearbyDeliveries = context.Deliveries
    .Where(d => d.Location.Distance(currentPosition) < 5000) // Within 5km
    .ToList();

In this example, the Distance method is translated by the provider into the database’s native spatial function (e.g., STDistance in SQL Server). This keeps the heavy lifting on the database engine, ensuring your spatial calculations remain performant without needing to pull vast amounts of data into memory. By integrating NetTopologySuite, you treat spatial coordinates as first-class citizens in your domain model, keeping your code clean and your database queries efficient.

Key Takeaway: By utilizing the NetTopologySuite library with EF Core, you can map complex geometric data types directly to your entities and execute high-performance spatial queries using standard LINQ.