如何在LINQ to Entities中获取最近的位置

时间:2013-07-25 13:50:40

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

我试图通过我的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中仅支持无参数构造函数和初始值设定项。

我尝试过Google搜索,但我仍然不确定如何修复它。什么是无参数构造函数?

2 个答案:

答案 0 :(得分:2)

您需要尝试这样做:

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; 

答案 1 :(得分:0)

问题在于这一行

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

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

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

相关问题