2015-08-21 65 views
-1

我有這個查詢即時嘗試按距離排序。但是,linq向我拋出一個錯誤,說它不能識別方法GetDistanceTo。查詢在OrderBy子句被取出時起作用。Linq不識別方法GetDistanceTo

var coord = new GeoCoordinate { Latitude = (double?)array.latitude ?? 0, Longitude = (double?)array.longitude ?? 0 }; 

var property = db.Properties.Select(x => new SearchResultsViewModel 
{ 
     geocoord = new GeoCoordinate { Latitude = (double?)x.latitude ?? 0, Longitude = (double?)x.longitude ?? 0 } 

}).OrderBy(x=>x.geocoord.GetDistanceTo(coord)).ToList(); 
+0

您是否試過[DbGeography](https://msdn.microsoft.com/en-us/library/system.data.spatial.dbgeography(v = vs.110).aspx)class? LINQ to SQL可能不支持'GeoCoordinate'。 – Guvante

+1

這是因爲它不知道如何將自定義方法'GetDistanceTo'轉換爲SQL。但是,您可以在'.OrderBy()'之前添加'.AsEnumerable()'來進行內存中的排序。 – Rob

回答

2

LINQ to Entities必須將您的表達式轉換爲可以針對數據庫執行的SQL查詢。它不知道如何將GetDistanceTo轉換爲SQL查詢。

您可以在OrderBy之前調用AsEnumerable強制執行內存中LINQ到對象查詢的排序。

var property = db.Properties.Select(x => new SearchResultsViewModel 
{ 
     geocoord = new GeoCoordinate { Latitude = (double?)x.latitude ?? 0, Longitude = (double?)x.longitude ?? 0 } 

}).AsEnumerable().OrderBy(x=>x.geocoord.GetDistanceTo(coord)).ToList(); 
相關問題