gpt4 book ai didi

c# - IsWithinDistance 无法翻译

转载 作者:行者123 更新时间:2023-12-04 08:26:39 27 4
gpt4 key购买 nike

我正在尝试返回给定位置 50 英里范围内的项目列表。
我的表(简化)如下:

  • 身份证
  • 经度
  • 纬度
  • 状态
  • 活跃

  • 我有一个初始查询:
    var query = db.MyTable.Where(o=> o.Status == "New" && o.Active == true);

    query = query.Where(o => new Point(o.Longitude, o.Latitude)
    .IsWithinDistance(new Point(_currentLongitude, _currentLatitude), 50));

    var result = query.ToList()
    但是 - 它似乎不起作用并且出现如下错误 - 任何想法如何解决这个问题?或者是否有更好的方法来获取最近的物品?

    .Where(p => new Point(p.Longitude, p.Latitude).IsWithinDistance(geom: __p_3,
    distance: ___maxDistance_4))' could not be translated.

    Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.


    启动.cs:
    services.AddDbContext<AppDbContext>(options =>
    {

    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
    x => x.UseNetTopologySuite());
    });

    最佳答案

    要使此功能起作用,您需要将这些坐标存储为 Point在 SQL 中 geography field 。您可以轻松地将此作为新属性上的计算列添加到现有模型中。

    // on your entity
    public Point Coordinates { get; }

    // in your db context's OnModelCreating
    modelBuilder.Entity<YourEntity>()
    .Property(x => x.Coordinates)
    .IsRequired()
    .HasComputedColumnSql("geography::Point(Latitude, Longitude, 4326)");
    请注意,SRID 4326 是 SQL Server 支持的常用经纬度坐标系。 More on that here .
    构建您的模型并部署到您的数据库。
    现在你有了一个空间字段和属性,你可以这样查询:
    var point = new Point(_currentLongitude, _currentLatitude) { SRID = 4326 };
    var distanceInMeters = 50 * 1609.344; // 50 miles to meters conversion
    var results = db.YourEntity
    .Where(x => x.Coordinates.IsWithinDistance(point, distanceInMeters))
    .ToList();
    SRID 4326 使用米表示距离,因此如果您使用英里,请务必按上图所示进行转换。
    此外,如果您有大量数据,您还需要在该列上添加空间索引,但是 EF Core doesn't support that directly yet所以你必须直接在 SQL 中做到这一点。

    关于c# - IsWithinDistance 无法翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65225029/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com