CHAPTER 6
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:
They offer similar operations, which include:
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 { get; set; }
public String Name { get; set; }
public DbGeography Location { get; set; } } |
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(); |