Skip to content

Spatial Types

Simon Hughes edited this page Oct 12, 2022 · 11 revisions

Generating code containing spatial types

Enable spatial types

Set the following in your <database>.tt file (approx line 85):

Settings.DisableGeographyTypes = false;

Disable spatial types

To not use spatial types at all, set the following in your <database>.tt file (approx line 85):

Settings.DisableGeographyTypes = true;

Using spatial types

When using database GEOGRAPHY or GEOMETRY types, for example in SQL Server:

CREATE TABLE Example
(
    [Id] INT NOT NULL PRIMARY KEY,
    GeographyType GEOGRAPHY NULL DEFAULT(CONVERT(GEOGRAPHY,'POINT (0 0)')),
    GeometryType GEOMETRY NULL DEFAULT(GEOMETRY::STGeomFromText('LINESTRING (100 100, 20 180, 180 180)', 0))
);

We need to map the GEOGRAPHY or GEOMETRY types to .NET CLR Types.

EF 6

In EF 6 these map to System.Data.Entity.Spatial.DbGeography and System.Data.Entity.Spatial.DbGeometry

EF Core

In EF.Core these map to NetTopologySuite.Geometries.Point and NetTopologySuite.Geometries.Geometry

In order to use NetTopologySuite, please read this article to install the correct NuGet package. For SQL Server this will be:

EF.Core 2

Install-Package Microsoft.EntityFrameworkCore.SqlServer.NetTopologySuite -Version 2.2.6
Install-Package dotMorten.Microsoft.SqlServer.Types -Version 1.3.0

EF.Core 3

Install-Package Microsoft.EntityFrameworkCore.SqlServer.NetTopologySuite -Version 3.1.22
Install-Package dotMorten.Microsoft.SqlServer.Types -Version 1.3.0

EF.Core 5

Install-Package Microsoft.EntityFrameworkCore.SqlServer.NetTopologySuite -Version 5.0.13

EF.Core 6

Install-Package Microsoft.EntityFrameworkCore.SqlServer.NetTopologySuite -Version 6.0.1

To enable mapping to spatial types via NetTopologySuite, call the UseNetTopologySuite method on the provider's DbContext options builder. For example, with SQL Server you'd call it like this:

optionsBuilder.UseSqlServer(
    @"Data Source=(local);Initial Catalog=YourDatabase;Integrated Security=True;Encrypt=false;TrustServerCertificate=true",
    x => x.UseNetTopologySuite());

Stored Procedures

If Settings.DisableGeographyTypes = true; and there is a stored procedure with either a spatial parameter or a return type which is a spatial type, the stored procedure is not generated.

More information

Please read this article