【问题标题】:GPS coordinates with Entity framework and LINQGPS 坐标与实体框架和 LINQ
【发布时间】:2012-03-28 18:08:41
【问题描述】:

所以根据我的阅读,实体框架还不支持 Geography SQL 类型。

我想知道是否有人可以解决我遇到的问题。我有一个 c# 类,它有一些使用实体框架和 LINQ 的数据访问方法。 这些方法将 GPS 坐标传递给它们。数据库(和实体框架类型)上有经度和纬度字段,这些字段在创建行时填充。这一切都很好。

我想要做的是让我的 LINQ 查询拉回给定 GPS 坐标附近(在半径内)的行。我不想开始使用存储过程,因为这将是架构更改。

有人对此有任何想法吗?我正在为想法而苦苦挣扎。

【问题讨论】:

    标签: c# .net linq entity-framework gps


    【解决方案1】:

    接受的答案已过期。 EF5 引入了用于处理空间数据的 API。这是来自 MSDN 的示例;

    型号

    using System.Data.Spatial; //For EF5
    //using System.Data.Entity.Spatial; //For EF6
    
    public class University  
    { 
        public int UniversityID { get; set; } 
        public string Name { get; set; } 
        public DbGeography Location { get; set; } 
    }
    

    数据库上下文

    using System.Data.Entity;
    
    public partial class UniversityContext : DbContext 
    { 
        public DbSet<University> Universities { get; set; } 
    }
    

    保存和检索数据

    using (var context = new UniversityContext ()) 
    { 
        context.Universities.Add(new University() 
            { 
                Name = "Graphic Design Institute", 
                Location = DbGeography.FromText("POINT(-122.336106 47.605049)"), 
            }); 
    
        context. Universities.Add(new University() 
            { 
                Name = "School of Fine Art", 
                Location = DbGeography.FromText("POINT(-122.335197 47.646711)"), 
            }); 
    
        context.SaveChanges(); 
    
        var myLocation = DbGeography.FromText("POINT(-122.296623 47.640405)"); 
    
        var university = (from u in context.Universities 
                            orderby u.Location.Distance(myLocation) 
                            select u).FirstOrDefault(); 
    
        Console.WriteLine( 
            "The closest University to you is: {0}.", 
            university.Name); 
    }
    

    上面的查询结果应该是The closest University to you is: School of Fine Art.

    whole article and video here.

    【讨论】:

      【解决方案2】:

      如果你想利用你的数据库空间索引(这将允许快速的空间查询),你应该将你的位置存储为Geography 在你的表中(如果你想,你也可以保留当前的纬度/经度列访问此值)。

      由于 Entity Framework 目前不支持 Geography 类型/函数,恐怕您唯一的选择是编写一个内部调用 STDistance 的存储过程(如果您使用 SQL Server 2008 R2)。

      老实说,由于空间函数实际上取决于数据库(STDistance 仅对 SQL Server 2008 R2 有效),因此为您的特定用例设置存储过程并不是一个坏主意。

      【讨论】:

      • 从 EF5 开始,添加了对 DbGeography 的支持。看我的回答。
      猜你喜欢
      • 2017-07-07
      • 1970-01-01
      • 2010-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-30
      • 2011-08-29
      相关资源
      最近更新 更多