PostGIS Entity Framework

可紊 提交于 2019-12-06 08:13:11

问题


I am trying to use Npgsql and Npgsql.EntityFramework with a geography data type. I can write data to the database, but I'm unable to retrieve it. I am not sure if this is even possible, so I would appreciate any help.

The class that represents 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 done like this:

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 retrieval is done like this:

using (var db = new Database.MyDbContext())
{
     var geos = from g in db.Geos
                     select g.Geography;
}

The problem is that I get the following error: Invalid cast from 'System.String' to 'System.Byte[]'.

I also tried saving the geography data as a string. In this case I am able to retrieve it, but I can't create a DbGeography object from text.

Any ideas? Thanks!

UPDATE:

The changes I made to ExpectedTypeConverter class:

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);
     }

来源:https://stackoverflow.com/questions/25549088/postgis-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!