在.NET Standard 2.0中的DbGeography

7

我希望使用asp .net core v2 web api服务进行一些空间计算。但由于.Net标准2.0缺乏对dbgeography空间类型的支持,我认为这是不可能的。目前是否有任何解决方法,直到dbgeography或其等效项得到支持?

2个回答

1

在尝试了不同的库之后,我最终自己制作了一个类。为了优化它,我想与大家分享。

- 场景:需要获取用户和商店之间的距离

- 商店类:

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); 并像这样使用它:

Location loc = new Location(_dbContext); var store = _dbContext.Store.FirstOrDefault(); loc.Longitude = 55.22; loc.Latitude = 33.55; var distance = store.Location.Distance(loc);

如果需要帮助,请随时与我联系。

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接