EF Code First(7)空间数据类型 Spatial Data Types

声明:本文针对 EF5+, Visual Studio 2012+

空间数据类型(Spatial Data Types)是在 EF5 中引入的,空间数据类型表现有两种:

  • Geography (地理学上的)- 存储的是椭圆形数据,如 GPS 的经纬度坐标;

  • Geometry (几何学上的)- 代表欧氏几何(平面的)坐标系统。

下面示例该数据类型的一个应用程序

新建 C# 控制台应用程序

相信 Console 应该都会建,命名为 SpatialCodeFirst

使用 Code First 建立 Model  

注意为 DbGeography 添加 System.Data.Entity.Spatial 命名空间

public class University
{
    public int UniversityID { get; set; }
    public string Name { get; set; }
    public DbGeography Location { get; set; }
}

定义DbContext 的派生类型

先要安装 Entity Framework (请参考 http://www.cnblogs.com/panchunting/p/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application.html

注意添加命名空间 System.Data.Entity, System.Data.Entity.ModelConfiguration.Conventions

class UniversityContext : DbContext
{
    public UniversityContext() : base("UniversityContext") { }

    public DbSet<University> Universities { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

定义UniversityInitializer

  注意添加命名空间 System.Data.Entity, System.Data.Entity.Spatial

class UniversityInitializer : DropCreateDatabaseIfModelChanges<UniversityContext>
{
    protected override void Seed(UniversityContext context)
    {
        var universities = new List<University>() { 
                new University { Name = "Graphic Design Institute", Location = DbGeography.FromText("POINT(-122.336106 47.605049)") },
                new University { Name = "School of Fine Art", Location = DbGeography.FromText("POINT(-122.335197 47.646711)") } 
            };
        universities.ForEach(s => context.Universities.Add(s));
        context.SaveChanges();
    }
}

配置App.config

注意黄色高亮部分,第一部分为配置数据库连接(使用 LocalDB ),第二部分为配置说明使用的 DbContext 及其初始化器

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>

  <connectionStrings>
    <add name="UniversityContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=SpatialCodeFirst;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <entityFramework>
    <contexts>
      <context type="SpatialCodeFirst.UniversityContext, SpatialCodeFirst">
        <databaseInitializer type="SpatialCodeFirst.UniversityInitializer, SpatialCodeFirst" />
      </context>
    </contexts>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

在 Program.cs 添加代码调用

class Program
{
    static void Main(string[] args)
    {
        using (var context = new UniversityContext())
        {
            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);
            Console.ReadKey();
        }
    }
}

运行查看结果

后台数据库定义

表中数据

(localdb)\v11.0不在列表中

右击新建 Connection 即可

原文: http://msdn.microsoft.com/en-us/data/hh859721