Planning To Use DbGeography And Points In EF: The Correct Format

7 September 2015

Here's a really quick gotcha if you're planning to use Entity Framework and Spatial columns with the DbGeography class support. As you're probably aware, you can't instantiate DbGeography directly, but you use methods instead, eg:

DbGeography.FromText();

This method takes in WKT / Well Known Text, which is apparently a standard. A standard that I can't seem to find the definitive documentation for...

MSDN isn't particularly helpful; but there are some examples online, like this page which is pretty high on Google search results. The code snippet from that site:

public static DbGeography ConvertLatLonToDbGeography(double longitude, double latitude)  
{
    var point = string.Format("POINT({1} {0})", latitude, longitude);
    return DbGeography.FromText(point);
}

You know what the best part is? It's wrong. The WKT for POINT expects it POINT(X, Y) - which is POINT(LON, LAT). And if you live in the UK, you may not notice immediately (or at least until you try and map your points).

So the main thing to take away is that to add a Point, provide it Longitude, Latitude. ie, use this code instead:

public static DbGeography ConvertLatLonToDbGeography(double longitude, double latitude)  
{
    var point = string.Format("POINT({1} {0})", longitude, latitude);
    return DbGeography.FromText(point);
}

Tags: DbGeography, EntityFramework, Spatial DB, WKT

Add a Comment

No Comments