空间-EF 设计器Spatial - EF Designer


EF5 仅向前 -实体框架5中引入了本页中所述的功能、api 等。EF5 Onwards Only - The features, APIs, etc. discussed in this page were introduced in Entity Framework 5. 如果使用的是早期版本,则部分或全部信息不适用。If you are using an earlier version, some or all of the information does not apply.

视频和分步演练演示了如何使用 Entity Framework Designer 映射空间类型。The video and step-by-step walkthrough shows how to map spatial types with the Entity Framework Designer. 它还演示了如何使用 LINQ 查询查找两个位置之间的距离。It also demonstrates how to use a LINQ query to find a distance between two locations.

本演练将使用 Model First 创建新的数据库,但 EF 设计器也可以与 Database First 工作流一起用于映射到现有数据库。This walkthrough will use Model First to create a new database, but the EF Designer can also be used with the Database First workflow to map to an existing database.

实体框架5中引入了空间类型支持。Spatial type support was introduced in Entity Framework 5. 请注意,若要使用空间类型、枚举和表值函数等新功能,则必须以 .NET Framework 4.5 为目标。Note that to use the new features like spatial type, enums, and Table-valued functions, you must target .NET Framework 4.5. 默认情况下,Visual Studio 2012 面向 .NET 4.5。Visual Studio 2012 targets .NET 4.5 by default.

若要使用空间数据类型,还必须使用具有空间支持的实体框架提供程序。To use spatial data types you must also use an Entity Framework provider that has spatial support. 有关详细信息,请参阅 提供程序对空间类型的支持See provider support for spatial types for more information.

主要的空间数据类型有两种:地理和几何。There are two main spatial data types: geography and geometry. Geography 数据类型存储椭圆体数据 (例如,GPS 纬度和经度坐标) 。The geography data type stores ellipsoidal data (for example, GPS latitude and longitude coordinates). Geometry 数据类型表示欧氏 (平面) 坐标系。The geometry data type represents Euclidean (flat) coordinate system.

观看视频Watch the video

此视频演示如何用 Entity Framework Designer 映射空间类型。This video shows how to map spatial types with the Entity Framework Designer. 它还演示了如何使用 LINQ 查询查找两个位置之间的距离。It also demonstrates how to use a LINQ query to find a distance between two locations.

提供者: Julia KornichPresented By: Julia Kornich

视频wmv | .wmv | wmv (ZIP) Video: WMV | MP4 | WMV (ZIP)


你将需要安装 Visual Studio 2012、旗舰版、高级版、专业版或 Web Express edition 才能完成此演练。You will need to have Visual Studio 2012, Ultimate, Premium, Professional, or Web Express edition installed to complete this walkthrough.

设置项目Set up the Project

  1. 打开 Visual Studio 2012Open Visual Studio 2012
  2. 在 "文件" 菜单上,指向 "新建",然后单击 "项目"On the File menu, point to New, and then click Project
  3. 在左窗格中,单击 " Visual # C",然后选择控制台模板In the left pane, click Visual C#, and then select the Console template
  4. 输入 SpatialEFDesigner 作为项目名称,然后单击 "确定"Enter SpatialEFDesigner as the name of the project and click OK

使用 EF 设计器创建新模型Create a New Model using the EF Designer

  1. 右键单击 "解决方案资源管理器中的项目名称,指向"添加",然后单击"新建项"Right-click the project name in Solution Explorer, point to Add, and then click New Item
  2. 从左侧菜单中选择 "数据",然后在 "模板" 窗格中选择 " ADO.NET 实体数据模型Select Data from the left menu and then select ADO.NET Entity Data Model in the Templates pane
  3. 输入UniversityModel作为文件名,然后单击 "添加"Enter UniversityModel.edmx for the file name, and then click Add
  4. 在 "实体数据模型向导" 页上,在 "选择模型内容" 对话框中选择 " 空模型 "On the Entity Data Model Wizard page, select Empty Model in the Choose Model Contents dialog box
  5. 单击“完成”Click Finish

此时会显示 Entity Designer,它提供了用于编辑模型的设计图面。The Entity Designer, which provides a design surface for editing your model, is displayed.

该向导执行下列操作:The wizard performs the following actions:

  • 生成 EnumTestModel 文件,该文件定义概念模型、存储模型和这些模型之间的映射。Generates the EnumTestModel.edmx file that defines the conceptual model, the storage model, and the mapping between them. 设置要嵌入到输出程序集的 .edmx 文件的元数据项目处理属性,以便将生成的元数据文件嵌入到程序集中。Sets the Metadata Artifact Processing property of the .edmx file to Embed in Output Assembly so the generated metadata files get embedded into the assembly.
  • 添加对以下程序集的引用: EntityFramework、System.componentmodel 和 DataAnnotations。Adds a reference to the following assemblies: EntityFramework, System.ComponentModel.DataAnnotations, and System.Data.Entity.
  • 创建 UniversityModel.tt 和 UniversityModel.Context.tt 文件,并将它们添加到 .edmx 文件下。Creates UniversityModel.tt and UniversityModel.Context.tt files and adds them under the .edmx file. 这些 T4 模板文件生成代码,该代码定义 DbContext 派生类型和映射到 .edmx 模型中的实体的 POCO 类型These T4 template files generate the code that defines the DbContext derived type and POCO types that map to the entities in the .edmx model

添加新的实体类型Add a New Entity Type

  1. 右键单击设计图面的空白区域,选择 " 添加 > 实体",此时将显示 "新建实体" 对话框。Right-click an empty area of the design surface, select Add -> Entity, the New Entity dialog box appears
  2. 指定类型名称的 大学 ,并为键属性名称指定 UniversityID ,将类型保留为 Int32Specify University for the type name and specify UniversityID for the key property name, leave the type as Int32
  3. 单击 “确定”Click OK
  4. 右键单击该实体,然后选择 "添加新 > 标量属性"Right-click the entity and select Add New -> Scalar Property
  5. 将新属性重命名为 名称Rename the new property to Name
  6. 添加另一个标量属性,并将其重命名为 Location 打开属性窗口并将新属性的类型更改为 GeographyAdd another scalar property and rename it to Location Open the Properties window and change the type of the new property to Geography
  7. 保存模型并生成项目Save the model and build the project


    生成时,有关未映射实体和关联的警告可能出现在错误列表中。When you build, warnings about unmapped entities and associations may appear in the Error List. 你可以忽略这些警告,因为在我们选择从模型生成数据库后,错误将消失。You can ignore these warnings because after we choose to generate the database from the model, the errors will go away.

从模型生成数据库Generate Database from Model

现在,我们可以生成一个基于该模型的数据库。Now we can generate a database that is based on the model.

  1. 右键单击 Entity Designer 图面上的空白区域,然后选择 "从模型生成数据库"Right-click an empty space on the Entity Designer surface and select Generate Database from Model
  2. 随即显示 "生成数据库" 向导的 "选择数据连接" 对话框,单击 "新建连接" 按钮,为数据库的服务器名称和大学指定** (localdb) \ Mssqllocaldb** ,并单击 "确定"The Choose Your Data Connection Dialog Box of the Generate Database Wizard is displayed Click the New Connection button Specify (localdb)\mssqllocaldb for the server name and University for the database and click OK
  3. 询问是否要创建新数据库的对话框将弹出,单击 "是"A dialog asking if you want to create a new database will pop up, click Yes.
  4. 单击 " 下一步 ",创建数据库向导将生成数据定义语言 (DDL) 用于创建数据库。在 "摘要和设置" 对话框中显示该 ddl 不包含映射到枚举类型的表的定义Click Next and the Create Database Wizard generates data definition language (DDL) for creating a database The generated DDL is displayed in the Summary and Settings Dialog Box Note, that the DDL does not contain a definition for a table that maps to the enumeration type
  5. 单击 " 完成 ",单击 "完成" 不执行 DDL 脚本。Click Finish Clicking Finish does not execute the DDL script.
  6. "创建数据库向导" 执行以下操作:在 T-sql 编辑器中打开 UniversityModel ,并生成 .edmx 文件的存储架构和映射部分,并将连接字符串信息添加到 App.config 文件中。The Create Database Wizard does the following: Opens the UniversityModel.edmx.sql in T-SQL Editor Generates the store schema and mapping sections of the EDMX file Adds connection string information to the App.config file
  7. 在 T-sql 编辑器中单击鼠标右键,然后选择 "执行连接到服务器" 对话框,输入步骤2中的连接信息,然后单击 "连接"Click the right mouse button in T-SQL Editor and select Execute The Connect to Server dialog appears, enter the connection information from step 2 and click Connect
  8. 若要查看生成的架构,请在 SQL Server 对象资源管理器中右键单击数据库名称,然后选择 "刷新"To view the generated schema, right-click on the database name in SQL Server Object Explorer and select Refresh

保留和检索数据Persist and Retrieve Data

打开 Program.cs 文件,其中定义了 Main 方法。Open the Program.cs file where the Main method is defined. 将以下代码添加到 Main 函数中。Add the following code into the Main function.

该代码将两个新的大学对象添加到上下文中。The code adds two new University objects to the context. 空间属性使用 DbGeography. FromText 方法进行初始化。Spatial properties are initialized by using the DbGeography.FromText method. 将 WellKnownText 表示的地理点传递给方法。The geography point represented as WellKnownText is passed to the method. 然后,该代码将保存数据。The code then saves the data. 然后,将构造并执行 LINQ 查询,该查询返回其位置与指定位置最接近的大学对象。Then, the LINQ query that that returns a University object where its location is closest to the specified location, is constructed and executed.

using (var context = new UniversityModelContainer())
    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)"),


    var myLocation = DbGeography.FromText("POINT(-122.296623 47.640405)");

    var university = (from u in context.Universities
                                orderby u.Location.Distance(myLocation)
                                select u).FirstOrDefault();

        "The closest University to you is: {0}.",

编译并运行该应用程序。Compile and run the application. 该程序生成以下输出:The program produces the following output:

The closest University to you is: School of Fine Art.

若要查看数据库中的数据,请在 SQL Server 对象资源管理器中右键单击数据库名称,然后选择 " 刷新"。To view data in the database, right-click on the database name in SQL Server Object Explorer and select Refresh. 然后,单击表上的鼠标右键,然后选择 " 查看数据"。Then, click the right mouse button on the table and select View Data.


在本演练中,我们介绍了如何使用 Entity Framework Designer 映射空间类型,以及如何在代码中使用空间类型。In this walkthrough we looked at how to map spatial types using the Entity Framework Designer and how to use spatial types in code.