I want to use asp .net core v2 web api service to do some spatial calculations. I believe that this is not possible because of the lack of support in Net standard 2.0 for dbgeography spatial type in .net standard 2.0. Is thre any workaround for this at the moment until such time as dbgeography or it's equivalent is suported?
I wanted to comment but I can't yet. Try checking out this post, it shows a turn around for using spatial operations: System.Data.Entity.Spatial replacement in ASP.NET Core
After trying different libraries i ended up making my own class. I would like to share it with you guys, in order to optimize it.
- Scenario : Need to get distance between User & Store
- Store Class :
public class Store
{
public int Id { get; set; }
public string Description { get; set; }
public string Name { get; set; }
public Location Location { get; set; }
}
- Location Class :
public class Location
{
public DataContext _dbContext { get; set; }
public Location()
{
}
public Location(DataContext dbContext)
{
_dbContext = dbContext;
}
public double Longitude { get; set; }
public double Latitude { get; set; }
public double Distance(Location destination, int srid=4326)
{
var source = this;
var Distance = string.Empty;
var query = @"DECLARE @target geography = geography::Point(" + destination.Latitude + @"," + destination.Longitude + @"," +srid+@")
DECLARE @orig geography = geography::Point(" + source.Latitude + @"," + source.Longitude + @"," + srid + @")
SELECT @orig.STDistance(@target) as Distance";
try
{
var dbConn = _dbContext.Database.GetDbConnection();
dbConn.Open();
var command = dbConn.CreateCommand();
command.CommandType = System.Data.CommandType.Text;
command.CommandText = query;
return Convert.ToDouble(command.ExecuteScalar().ToString());
}
catch (Exception ex)
{
Error.LogError(ex);
throw ex;
}
}
}
Make sure to add data annotation [NotMapped] on Location Property in Store Class or add follwoing line in your Data Context Class :
modelBuilder.Entity<Store>().OwnsOne(c => c.Location);
And use it like this
Location loc = new Location(_dbContext); var store = _dbContext.Store.FirstOrDefault(); loc.Longitude = 55.22; loc.Latitude = 33.55; var distance = store.Location.Distance(loc);
In case of help you can contact me anytime.
© 2022 - 2024 — McMap. All rights reserved.