I\'m experimenting with entity framework core and stumbled upon an error I\'ve never seen before and can\'t figure out how to fix it. I\'m using .net Core Web API 2.0 with E
These solutions work but if you are looking for additional ways here is another solution. Since EF core 2 does not support geography types at this time you can use NetTopologySuite for all you server side geography support.
When you have a table that needs a geography column add property that EF can map to your table that either has type byte[] or string. Like so:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NetTopologySuite;
using NetTopologySuite.Geometries;
namespace GeoTest2.Data
{
public class HomeTown
{
private byte[] _pointsWKB;
public string Name { get; set; }
public byte[] PointWkb
{
get => _pointsWKB;
set
{
if (GeopgraphyFactory.CreatePoint(value) != null)
_pointsWKB = value;
throw new NotImplementedException("How ever you wnat to handle it");
}
}
[NotMapped]
public Point Point
{
get => GeopgraphyFactory.CreatePoint(_pointsWKB);
set => _pointsWKB = GeopgraphyFactory.PointAsWkb(value);
}
}
}
This uses some helpers for creating points where are here:
using NetTopologySuite.Geometries;
namespace GeoTest2.Data
{
public static class GeopgraphyFactory
{
public static Point CreatePoint(byte[] wkb)
{
var reader = new NetTopologySuite.IO.WKBReader();
var val = reader.Read(wkb);
return val as Point;
}
public static byte[] PointAsWkb(Point point)
{
var writer = new NetTopologySuite.IO.WKBWriter();
return writer.Write(point);
}
}
}
As you can see nothing special is going on here. This code in place you should have Full CRUDS. If you need geography support on the db side as well (like our team did) then you can create a calculated column that uses this data to generate the correct geography type like so:
ALTER TABLE dbo.tableName
ADD Point AS
CONVERT(
GEOGRAPHY,
CASE WHEN [GeographyWkb] IS NOT NULL THEN
GEOGRAPHY::STGeomFromWKB ( [GeographyWkb], 4326 )
ELSE NULL
END)
EF will ignore this calculated column and you will be able to use it db side. Now this does leave use to how you would handle spatial queries and that is left to the reader. There are a number of ways to handle it and some of the answers above show some of them. It is worth noting if the query is small you could do it in memory with NetTopologySuite, since the library provides support for unions, intersections, etc...