如何使用此linq查询获取驱动程序ID列

时间:2018-12-26 11:52:24

标签: c# sql-server linq

我的SQL Server数据库具有表DriverLocation,其中包含有关

的数据
DriverId
DriverLatitude
DriverLongitude

表格图片

enter image description here

我将传递客户纬度,经度作为以下代码的参数,并获得DriverId作为回报,并按最近的Latitude,Longitude排序。

使用以下代码,我可以根据DriverLatitude,DriverLongitude获得最近的位置。但是我无法获得DriverId

有人可以建议通过修改此处显示的linq查询来获取DriverId作为输出的方法吗?

public ActionResult ClosestDriverList(double Latitude, double Longitude)
{
    using (DataContext DbContextHelper = new DataContext())
    {
        var coord = new GeoCoordinate(Latitude, Longitude);
        var nearest = DbContextHelper.DriverLocationModels.Select(x => new
        {
            geocoord = new GeoCoordinate
            {
                Latitude = (double?)x.DriverLatitude ?? 0,
                Longitude = (double?)x.DriverLongitude ?? 0
            }
        }).AsEnumerable().OrderBy(x => x.geocoord.GetDistanceTo(coord));
    }

    return View();
}

2 个答案:

答案 0 :(得分:1)

按照@elgonzo的建议,在您的geocoord下为DriverId添加属性

public ActionResult ClosestDriverList(double Latitude, double Longitude)
{
    using (DataContext DbContextHelper = new DataContext())
    {
        var coord = new GeoCoordinate(Latitude, Longitude);
        var nearest = DbContextHelper.DriverLocationModels.Select(x => new
        {
            geocoord = new GeoCoordinate
            {
                Latitude = (double?)x.DriverLatitude ?? 0,
                Longitude = (double?)x.DriverLongitude ?? 0
            },
            x.DriverId  // <----- this is what you're missing
        }).AsEnumerable().OrderBy(x => x.geocoord.GetDistanceTo(coord));
    }

    return View();
}

答案 1 :(得分:0)

在对Select()的呼叫中包含ID。如果您不这样做,则代码将仅采用坐标。因此,将您的代码更新为:

public ActionResult ClosestDriverList(double Latitude, double Longitude)
{
    using (DataContext DbContextHelper = new DataContext())
    {
        var coord = new GeoCoordinate(Latitude, Longitude);
        var nearest = DbContextHelper.DriverLocationModels.OrderBy(d =>
            coord.DistanceTo(
                new GeoCoordinate
                {
                    Latitude = (double?)d.DriverLatitude ?? 0,
                    Longitude = (double?)x.DriverLongitude ?? 0
                }
            )
        ).FirstOrDefault()?.DriverId ?? 0;

     }
      return View();
}