Entity Framework Core saving geography::Point throws "The supplied value is not a valid instance of data type geography"

Viewed 25

When trying to insert a row that has a property of type NetTopologySuite.Point I get an exception

The supplied value is not a valid instance of data type geography

Steps to reproduce:

(1) Create a new console app.

(2) Add the following references

<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.NetTopologySuite" Version="6.0.9" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" />

(3) Create the following domain class

public class SomewhereNice
{
    public int Id { get; set; }
    public string Name { get; set; } = "The sea";
    public Point Location { get; set; } = new Point(0, 0, 4326);
}

(4) Add a DbContext descendant

public class ApplicationDbContext : DbContext
{
    public DbSet<SomewhereNice> NicePlaces { get; set; } = null!;
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) {}
}

(5) Update the Program.cs file as follows and then run the app....

using EFGeography;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

Console.WriteLine("Hello, World!");

var services = new ServiceCollection();

services.AddDbContext<ApplicationDbContext>(options =>
{
    options.UseSqlServer(
        connectionString: "Server=.\\SQLExpress;Database=EFGeography;Trusted_Connection=True;MultipleActiveResultSets=true",
        x => x.UseNetTopologySuite());
});

IServiceProvider serviceProvider = services.BuildServiceProvider();

using var context = serviceProvider.GetRequiredService<ApplicationDbContext>();
context.Database.EnsureCreated();

var theSea = new SomewhereNice();
context.NicePlaces.Add(theSea);
context.SaveChanges();

I have checked, and SRID 4326 does exist.

select *
from sys.spatial_reference_systems
where authorized_spatial_reference_id = 4326
1 Answers

new Point(0, 0, 4326) creates a point X,Y,Z

What I needed was

new Point(0, 0) { SRID = 4326 };
Related