使用MySQL和EntityFramework的DbGeography

7

我正在使用来自 System.Data.Entity.Spatial; 和 Entity Framework 的 DbGeography,与 SQL Server 数据库一起使用。现在我要切换到使用 MySQL 服务器,但是在创建与 DbGeography 类型相关的数据库时出现错误。

我如何解决这个问题而不改变所有域类属性的类型?

public class Place
{
  ...
    public virtual int Id { get; set; }
    public string Name { get; set; }
    public DbGeography Location {get;set;}
  ...

}

我遇到的错误是这样的:
System.NotSupportedException: There is no store type corresponding to the EDM type 'Edm.Geography' of primitive type 'Geography'.
2个回答

4
我翻译的结果如下:

我查阅了大量MySQL文档,发现mysql 5.x目前不支持DbGeography数据类型。

只有DbGeometry被mysql 5.x支持。我感到沮丧。

请参考MySQL官方空间数据支持文档

Entity Framework支持两种主要的空间数据类型:DbGeometry和DBGeography。由于MySQL服务器没有任何等价的类型可以映射到此类型,因此Connector/Net不支持第二个类型。所以所有示例都将使用DbGeometry类型。

也许您可以使用DbGeometry数据类型的POINT来保存经度和纬度,然后使用Haversine公式计算距离。


1
正如ehe888所指出的那样,MySQL Connector/Net不支持映射到DbGeography,但支持映射到DbGeometry
如果您只需要存储一个POINT自版本6.10起,MySQL Connector/Net仅支持此几何类型),那么您可以在实体中轻松地在DbGeographyDbGeometry之间进行转换。
    [Column("gps_location")]
    public DbGeometry LocationGeometry { get; set; }

    [NotMapped] // Mapping to DbGeography is not supported by MySQL Connector/Net, see https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework50.html
    public DbGeography Location
    {
        get => LocationGeometry != null ? DbGeography.FromBinary(LocationGeometry.AsBinary()) : null;
        set => LocationGeometry = value != null ? DbGeometry.FromBinary(value.AsBinary()) : null;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接