public Location GetByGeoPoint( DbGeography point )
{
// get the first address that has a GeoPoint the value
// use the 'Where Max(ID)' trick instead of TOP 1 to optimize SQL performance
var qryWhere = Queryable()
.Where( a =>
a.GeoPoint != null &&
a.GeoPoint.SpatialEquals( point ) );
var result = Queryable().Where( a => a.Id == qryWhere.Max( b => b.Id ) ).FirstOrDefault();
if ( result == null )
{
// if the Location can't be found, save the new location to the database
Location newLocation = new Location
{
GeoPoint = point,
Guid = Guid.NewGuid()
};
// Create a new context/service so that save does not affect calling method's context
var rockContext = new RockContext();
var locationService = new LocationService( rockContext );
locationService.Add( newLocation );
rockContext.SaveChanges();
// refetch it from the database to make sure we get a valid .Id
return Get( newLocation.Guid );
}
return result;
}