【发布时间】:2018-08-20 14:57:26
【问题描述】:
我想使用 asp .net core v2 web api 服务来做一些空间计算。我认为这是不可能的,因为 Net 标准 2.0 中缺乏对 .net 标准 2.0 中 dbgeography 空间类型的支持。目前是否有任何解决方法,直到支持 dbgeography 或它的等价物?
【问题讨论】:
我想使用 asp .net core v2 web api 服务来做一些空间计算。我认为这是不可能的,因为 Net 标准 2.0 中缺乏对 .net 标准 2.0 中 dbgeography 空间类型的支持。目前是否有任何解决方法,直到支持 dbgeography 或它的等价物?
【问题讨论】:
我想发表评论,但我还不能。试试看这篇文章,它展示了使用空间操作的转变:System.Data.Entity.Spatial replacement in ASP.NET Core
【讨论】:
在尝试了不同的库之后,我最终创建了自己的课程。分享给大家,以便优化。
- 场景:需要获取用户和商店之间的距离
- 商店类:
public class Store
{
public int Id { get; set; }
public string Description { get; set; }
public string Name { get; set; }
public Location Location { get; set; }
}
- 位置类:
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;
}
}
}
确保在 Store 类的 Location 属性上添加数据注释 [NotMapped] 或在您的数据上下文类中添加以下行:
modelBuilder.Entity<Store>().OwnsOne(c => c.Location);
并像这样使用它
位置 loc = new Location(_dbContext); var store = _dbContext.Store.FirstOrDefault(); loc.Longitude = 55.22; loc.Latitude = 33.55; var distance = store.Location.Distance(loc);
如有需要可以随时联系我。
【讨论】: