public Location GetByGeoFence( DbGeography fence )
{
// get the first address that has the GeoFence value
// use the 'Where Max(ID)' trick instead of TOP 1 to optimize SQL performance
var qryWhere = Queryable()
.Where( a =>
a.GeoFence != null &&
a.GeoFence.SpatialEquals( fence ) );
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
{
GeoFence = fence,
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;
}