Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spatial data types support in Linq2Sql or EF4

Tags:

Does anyone know (ideally, with a reference), whether the VS2010 release of LinqToSQL or EntityFramework v4 will support queries over the SQL 2008 spatial data types?

like image 849
Colin Desmond Avatar asked Aug 21 '09 22:08

Colin Desmond


People also ask

Which class does support spatial data in Entity Framework?

public partial class Student. { public int ID { get; set; }

What are spatial data types?

1.3. Spatial data are of two types according to the storing technique, namely, raster data and vector data.

Which is an example of spatial data type supported by SQL Server?

SQL Server supports two spatial data types: the geometry data type and the geography data type.

What is NetTopologySuite?

NetTopologySuite (NTS) is a spatial library for . NET. EF Core enables mapping to spatial data types in the database by using NTS types in your model. To enable mapping to spatial types via NTS, call the UseNetTopologySuite method on the provider's DbContext options builder.


1 Answers

Here's a workaround to get it working in Entity Framework / LINQ to Entities:

You can use a database View to return Well-Known-Text (using "geometry.ToString()" in the query) or Binary. Then once the resulting rows are returned, just convert the string/binary to a SqlGeometry object in .NET.

Here's a sample query used to build a View that converts a "Location" field of geometry type to a Well-Known-Text String:

SELECT ID, Name, Location.ToString() as Location FROM MyTable

Here's an example of querying the resulting entities that have a "Location" field that contains a Well-Known-Text or String representation of the "geography" object:

var e = new MyApp.Data.MyDataEntities(connectionString);
var items = from i in e.MyTables
            select i;

foreach (var i in items)
{
    // "Location" is the geography field
    var l = SqlGeography.Parse(i.Location);
    var lat = l.Lat;
    var lng = l.Long;
}

One additional thing, is you'll need to do any spatial based queries within Stored Procedures, since you don't want to pull ALL the data from the table into .NET in order to perform your own spatial query using LINQ.

This isn't an elegent as natively supporting SQL Spatial Types, but it'll get you running with Entity Framework and SQL Spatial simultaneously.

like image 122
Chris Pietschmann Avatar answered Oct 02 '22 01:10

Chris Pietschmann