1

I have some older methods using sql strings and connections that I'm trying to convert to Linq to Entities.

I have rewritten the sql to an ef query as follows;

Using ctx As New DataEntities()
        Dim station As String = (From sta In ctx.weather_stations
                                 Let distance = SqlFunctions.SquareRoot(Math.Pow(69.1 * (sta.latitude - lat), 2) + Math.Pow(69.1 * (longi - sta.longitude) * SqlFunctions.Cos(sta.latitude / 57.3), 2))
                                 Where distance < withinRange
                                 Order By distance
                                 Select sta.station_id).Take(1).ToString()
        If Not String.IsNullOrEmpty(station) Then
            Return station
        Else
            Return String.Empty
        End If
    End UsingData

This gives an error, LINQ to Entities does not recognize the method 'Double Sqrt(Double)' method, and this method cannot be translated into a store expression.

Can this query be done in Linq to EF? If so, how can I reconstruct this query to work?

dinotom
  • 4,990
  • 16
  • 71
  • 139
  • 1
    See here: http://stackoverflow.com/questions/9354716/linq-to-ef-unsupported-functions; you need to use the `SqlFunctions` static helper class. – Stephen Byrne Oct 23 '13 at 16:16
  • That does solve the sqrt problem but im getting this error now on cos, – dinotom Oct 23 '13 at 16:34
  • The specified method 'System.Nullable`1[System.Double] Cos(System.Nullable`1[System.Double])' on the type 'System.Data.Objects.SqlClient.SqlFunctions' cannot be translated into a LINQ to Entities store expression. See my query edit above – dinotom Oct 23 '13 at 16:35
  • The sta.longitude is NOT a nullable value. – dinotom Oct 23 '13 at 16:36
  • IT does not have to be. There is implicit conversion between `T` and `Nullable` defined. – MarcinJuraszek Oct 23 '13 at 16:43
  • @MarcinJuraszek...Then how do I change the query to satisfy this error? – dinotom Oct 23 '13 at 18:20
  • You changed `Math.Sqrt` into `SqlFunctions.SquareRoot`, but nothing else. I would have expected the exception to disappear. Is there still a problem? – Gert Arnold Oct 29 '13 at 21:13

0 Answers0