2016-01-20

Spatial data (longtitute/latitude) with Entity Framework (C#)

Spatial type was introduced in Entity Framework 5. To use this new feature (spatial type, enums and Table-valued functions) you must target .NET Framework 4.5 or newer.
There are two main spatial data types: geography and geometry. The geofraphy data type stores ellipsoidal data (for example GPS latitude and longtitude coordinates). The geometry data type represents Euclidean (flat) coordinate system.

Define a Model using Code First:
using System.Data.Spatial;

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

public partial class UniversityContext : DbContext 
{ 
    public DbSet Universities { get; set; } 
}

Persist and Retrieve Data:
using (var context = new UniversityContext ()) 
{ 
    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)"), 
        }); 
 
    context.SaveChanges(); 
 
    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); 
}

No comments:

Post a Comment