PostGIS Entity Framework
I am trying to use Npgsql and Npgsql.EntityFramework with geography datatype. I can write data to the database, but I cannot restore it. I'm not sure if this is possible, so I would appreciate any help.
The class representing the table looks like this:
internal class Geo
{
[Key, Column("geo_test_id")]
public int GeoId { get; set; }
[Column("geography")]
public byte[] Geography { get; set; }
}
Data insertion is performed as follows:
var geog1 = System.Data.Spatial.DbGeography.FromText("POINT(-118.4079 33.9434)");
var geog2 = System.Data.Spatial.DbGeography.FromText("POINT(2.5559 49.0083)");
using (var db = new Database.MyDbContext())
{
db.Geos.Add(new Database.Geo() { Geography = geog1.AsBinary() });
db.Geos.Add(new Database.Geo() { Geography = geog2.AsBinary() });
db.SaveChanges();
}
Data search is performed as follows:
using (var db = new Database.MyDbContext())
{
var geos = from g in db.Geos
select g.Geography;
}
The problem is that I am getting the following error: Invalid cast from 'System.String' to 'System.Byte[]'.
I also tried to store the geography data as a string. In this case, I can get it, but I cannot create a DbGeography object from text.
Any ideas? Thank!
UPDATE:
Changes I made to the class ExpectedTypeConverter
:
else if (expectedType == typeof(byte[]))
{
if (currentType == typeof(Guid))
{
return ((Guid)value).ToByteArray();
}
else if (value is Array)
{
Array valueArray = (Array)value;
int byteLength = Buffer.ByteLength(valueArray);
byte[] bytes = new byte[byteLength];
Buffer.BlockCopy(valueArray, 0, bytes, 0, byteLength);
return bytes;
}
else if (currentType == typeof(System.String)) // this part was added
{
string hex = value.ToString();
int numChars = hex.Length / 2;
byte[] bytes = new byte[numChars];
using (var sr = new StringReader(hex))
{
for (int i = 0; i < numChars; i++)
{
bytes[i] = Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);
}
}
return bytes;
}
else
{
// expect InvalidCastException from this call
return Convert.ChangeType(value, expectedType);
}
source to share
No one has answered this question yet
See similar questions:
or similar: