PostGISentity framework

我试图使用Npgsql和Npgsql.EntityFramework与地理数据类型。 我可以将数据写入数据库,但我无法检索它。 我不确定这是否可行,所以我将不胜感激。

表示该表的类如下所示:

internal class Geo { [Key, Column("geo_test_id")] public int GeoId { get; set; } [Column("geography")] public byte[] Geography { get; set; } } 

数据插入如下所示:

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

数据检索是这样完成的:

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

问题是我收到以下错误: Invalid cast from 'System.String' to 'System.Byte[]'.

我还尝试将地理数据保存为字符串。 在这种情况下,我能够检索它,但我无法从文本创建DbGeography对象。

有任何想法吗? 谢谢!

更新:

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