In my .NET Core application, I'm trying to read spatial data types (NetTopologySuite's Geometry) from a SqlCommand object using this code:
using (var result = command.ExecuteReader())
{
var entities = new List<Geometry>();
while (result.Read())
{
var geometryReader = new SqlServerBytesReader { IsGeography = false };
var bytes = result.GetSqlBytes(0).Value;
var geometry = geometryReader.Read(bytes);
entities.Add(geometry);
}
connection.Close();
return entities;
}
It's working fine. But the problem that I can't use a single generic method for all not spatial data types:
using (var result = command.ExecuteReader())
{
var entities = new List<T>();
while (result.Read())
{
entities.Add((T)result.GetValue(0));
}
connection.Close();
return entities;
}
I tried to use this snippet to read Geometry but got an error:
Unable to cast object of type 'Microsoft.SqlServer.Types.SqlGeometry' to type 'Microsoft.Data.SqlClient.Server.IBinarySerialize'.
Am I missing something and is it possible to read all spatial data types with the same generic code?