【问题标题】:How to Get Closest Location in LINQ to Entities如何在 LINQ to Entities 中获取最近的位置
【发布时间】:2013-07-25 13:50:39
【问题描述】:

我正在尝试通过我的 LINQ 查询获取最近的位置:

var coord = new GeoCoordinate(loc.Latitude, loc.Longitude);
var nearest = ctx.Locations
                 .Select(x => new LocationResult {
                     location = x,
                     coord = new GeoCoordinate(x.Latitude.GetValueOrDefault(),
                                               x.Longitude.GetValueOrDefault())
                 })
                 .OrderBy(x => x.coord.GetDistanceTo(coord))
                 .First();

return nearest.location.Id; 

但是,我收到以下错误:

LINQ to Entities 仅支持无参数构造函数和初始化程序。

我试过用谷歌搜索,但我仍然不确定如何解决它。什么是无参数构造函数?

【问题讨论】:

  • 是否可以写成:new GeoCoordinate{x.Latitude.GetValueOrDefault(), x.Longitude.GetValueOrDefault()}
  • @jyparask - 嗯?这甚至不会建立。
  • 可以分享LocationResult类吗?

标签: c# linq entity-framework linq-to-entities


【解决方案1】:

你需要试试这个:

var coord = new GeoCoordinate(loc.Latitude, loc.Longitude);
                var nearest = ctx.Locations
                    .Select(x => new LocationResult {
                        location = x,
                        coord = new GeoCoordinate { Latitude = x.Latitude ?? 0, Longitude = x.Longitude ?? 0 }
                    })
                    .OrderBy(x => x.coord.GetDistanceTo(coord))
                    .First();

                return nearest.location.Id; 

【讨论】:

  • 谢谢,但现在我收到以下错误LINQ to Entities does not recognize the method 'Double GetValueOrDefault()' method, and this method cannot be translated into a store expression.
  • @user1477388 试试x.Latitude ?? 0。 Linq to Entities 识别空合并运算符。
  • @SimonBelanger 这可能有用,谢谢;但我只是尝试在我的.Select() 之前添加.AsEnumerable() 并且它有效。
  • @user1477388 它会,但你会得到整张桌子。 AsEnumerable 退出实体框架的 IQueryProvider 世界。由于您使用的是First,因此我强烈建议您不要使用AsEnumerable,以避免获取比所需更多的记录。
  • @SimonBelanger 我尝试过使用Latitude = x.Latitude ?? 0Longitude,但它给了我同样的错误。
【解决方案2】:

问题出在这一行

new GeoCoordinate(x.Latitude.GetValueOrDefault(), x.Longitude.GetValueOrDefault())

这是使用带有参数的构造函数,因为 GeoCoordiante 类的构造函数是使用几个参数调用的。

无参数构造函数是不带任何参数的类型的构造函数。

【讨论】:

  • 对,这个完全没用。
  • @newStackExchangeInstance - 有用的评论!
  • 感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多