Saturday, February 19, 2011

Entity Frameworks and Spatial Data

So as part of my new job I've begun self edification in ORM (Object Relational Modeling). I've been asked to evaluate methods to use .Net 4.0 Entity Frameworks with spatial data. The rub being that the framework currently doesn't support SQL server's spatial types.

After a lot of reading and some experimentation I think I've found a solution. There are some basic requrements I am trying to meet. First the solution needs to accommodate frequent rebuilds of the edmx model. I expect developers on my team to be making frequent changes and I don't want to be constantly making hand edits to xml. Second I need to allow for spatial queries - can't just axe spatial support altogether.

So first I built the model from the database using the wizard. No problem - I get the usual warnings that the tool will skip spatial types. No way to access the spatial data via EF.

I read that we can store spatial data as a varbinary in sql server. So back to the db to add a binary column. Put on a trigger to handle keeping the spatial column and the binary data in sync with a re-cast of binary data inserts or updates. Now back to visualstudio to rebuild the edmx. Sure enough same warnings but now I have my binary column that I can, with the addition of a patial class, cast to a spatial object. Additional casts back in the set method and I'm writting binary data back through EF. With my after insert trigger to keep things copacetic I am in business!

Just have to add some stored proceedures or explicit sql for spatial queries and done.