Entity Framework Tutorial Basics(33):Spatial Data type support in Entity Framework 5.0

追憶似水流年發表於2016-07-07

Spatial Data type support in Entity Framework 5.0

MS SQL Server 2008 introduced two spatial data types, geography and geometry. Geography represents data in a round-earth coordinate system and geometry represent data in a Euclidean (flat) coordinate system.

Entity Framework supports spatial data types DbGeography and DbGeometry since version 5.0. Let's see how we can use these data types.

For demo purposes, we have changed the data type of the Location column of Course table to geography in SQL Server 2008 as shown below:

Entity Framework 5.0 Tutorial

Now, create an entity data model (.edmx) after having geography column in the database as shown in previous chapter section. After creating EDM, you can see that the type of Location property of Course entity is System.Data.Spatial.DBGeography as shown below:

public partial class Course
{
    public Course()
    {
        this.Students = new HashSet<Student>();
    }
    
    public int CourseId { get; set; }
    public string CourseName { get; set; }
    public Nullable<int> TeacherId { get; set; }
    public System.Data.Spatial.DbGeography Location { get; set; }
    
    public virtual Teacher Teacher { get; set; }
    public virtual ICollection<Student> Students { get; set; }
}

 

You can now use the Location property in CRUD operation using DBContext as shown in the following example.

using (var ctx = new SchoolDBEntities())
{
    ctx.Courses.Add(new Course() { CourseName = "New Course", 
                Location = DbGeography.FromText("POINT(-122.360 47.656)") });

    ctx.SaveChanges();
}

 

Visit MSDN for more information on geography data type and geometry data type of MS SQL Server 2008.

相關文章