left-icon

Entity Framework Code First Succinctly®
by Ricardo Peres

Previous
Chapter

of
A
A
A

CHAPTER 6

Spatial Data Types

Spatial Data Types


Overview

SQL Server 2008 introduced two spatial data types. These offer the ability to write geographically-oriented queries in a more natural way, because the server knows about coordinates, distances, and so on. These types are:

  • GEOMETRY: Euclidean (flat space) standard operations, defined by the Open Geospatial Consortium (OGC).
  • GEOGRAPHY: Round-Earth operations, also defined by OGC.

They offer similar operations, which include:

  • Calculating the distance between two points.
  • Checking if a point is included in a polygon.
  • Getting the intersection of two polygons.

Spatial types are not an exclusive of SQL Server, but not all Entity Framework providers support them; for more information, check out Entity Framework Provider Support for Spatial Types: http://msdn.microsoft.com/en-us/data/dn194325.aspx.

Entity Framework handles the spatial types pretty much like it does all other types. Namely, it can generate databases from entities containing properties of spatial types and uses LINQ for querying these types. Their .NET counterparts are DbGeography and DbGeometry.

A detailed explanation of these types is outside the scope of this chapter, so I’ll just leave some querying examples.

First, let’s start with a class with a geographical property.

public class Venue

{

  public Int32 VenueId { getset; }

 

  public String Name { getset; }

 

  public DbGeography Location { getset; }

}

As an appetizer, two simple queries for calculating the distance between a fixed location point and some venues and for checking the points that fall inside an area using LINQ are as follows.

//a fixed location in Well-known Text (WKT) format

var location = DbGeography.FromText(string.Format("POINT({0} {1})", 41, 8));

//an area in WKT and Spatial Reference System Identifier (SRID) 4326

var area = DbGeography.MultiPointFromText("MULTIPOINT(53.095124 -0.864716, 53.021255 -1.337128, 52.808019 -1.345367, 52.86153 -1.018524)", 4326);

//the distance from all stored locations to the fixed location

var venuesAndDistanceToLocation = ctx.Venues

.OrderBy(v = v.Location.Distance(location))

.Select(v => new { Venue = v, Distance = v.Location.Distance(location) }).ToList();

//venues inside the area

var pointInsideArea = ctx.Venues.Where(x => area.Intersects(x.Location)).ToList();

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.