Search code examples
sql-servergeospatialspatialef-core-2.2asp-net-core-spa-services

Entity Framework Core + Spatial Data is Raising SRID not vaild error


I'm getting the following error:

ERROR: SqlException: .NET Framework error during routine execution or user-defined aggregate 'geography': System.ArgumentException: 24204: spatial reference identifier (SRID) is not valid. The specified SRID must match one of the supported SRIDs shown in the sys.spatial_reference_systems catalog view.

This error is raised when I'm trying to save to SQL DB a point created like this

new Point(it.Lat, it.Lng)

After that I'v tried to use a GeometryFactory like this one:

    public static class GeometryHelper
    {
        public static IGeometryFactory GeometryFactory { get; set; }
            = NtsGeometryServices.Instance.CreateGeometryFactory();
    }
...
    geometryFactory.CreatePoint(new Coordinate(it.Lat, it.Lng))

And nothing.

Also tried setting a specific SRID:

    public static class GeometryHelper
    {
        public static IGeometryFactory GeometryFactory { get; set; }
            = NtsGeometryServices.Instance.CreateGeometryFactory(4326);
    }

But then get this error:

SqlException: .NET Framework error during routine execution or user-defined aggregate 'geography': System.FormatException: One of the identified elements has an invalid format. System.FormatException:


Solution

  • Solved a few minutes after posting the question. About the first error, the right way of solving it is doing what is in the question: Creating a geometry factory and use 4326 as SRID. You must check that the SRID you use is in the database table (sys.spatial_reference_systems catalog view). Apparently 4326 is a standard one as it is in the Microsft documentation.

        public static class GeometryHelper
        {
            public static IGeometryFactory GeometryFactory { get; set; }
                = NtsGeometryServices.Instance.CreateGeometryFactory(4326);
        }
    

    The second error was related to the mapping between points and lat-lng objects.

    Longitude and Latitude Coordinates in NTS are in terms of X and Y values. To represent longitude and latitude, use X for longitude and Y for latitude. Note that this is backwards from the latitude, longitude format in which you typically see these values.

    Reference: Spatial in Ef Core