Maybe I'm missing something. I have a sql server column of the "Geography" datatype.
I want to use the DbGeography type in my c# code. Any way to cast or convert from sql's geography to dbgeography?
When the performance is of any importance, the well-known binary should be used instead of the well-known text:
var newGeography = DbGeography.FromBinary(theGeography.STAsBinary().Value);
There is an overload using a SRID, if that is important. In my simple test with a 1,000 reasonably complicated polygons the binary-based approach is 4 times faster than the text-based one:
* Binary-based conversion
Run 1: 1948
Run 2: 1944
Run 3: 1959
Run 4: 1979
Run 5: 1988
Average: 1963.6
* Text-based conversion
Run 1: 8527
Run 2: 8553
Run 3: 8596
Run 4: 8535
Run 5: 8496
Average: 8541.4
Sorry for the late response - but saw this whilst searching for something else.
Simply do the following:
SqlGeography theGeography;
int srid = 4326; // or alternative
DbGeography newGeography = DbGeography.FromText(theGeography.ToString(), srid);
To reverse it:
DbGeography theGeography;
SqlGeography newGeography = SqlGeography.Parse(theGeography.AsText()).MakeValid();
Hope that helps!
The provided solution seems to be ok if you are not running EF6. With early versionsit´s ok, but with EF6, we shouldnt make references to this assembly. It turns EF litle crazy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With