none
using Math.cos in linq to entities RRS feed

  • Question

  • 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) * Math.Cos(sta.latitude / 57.3), 2))
                                         Where distance < 10
                                         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 Cos(Double)' method, and this method cannot be translated into a store expression

    The same is true when I try to use SqlFunctions.Cos

    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.



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

    Thomas Donino Visual Studio 2010 on Windows 7

    Wednesday, October 23, 2013 7:44 PM

Answers

  • Hello,

    What version Entity Framework have you used?

    I tested the codes and it would work fine with SqlFunction.Cos() method like below:

    var result = (from r in db.Roles
    
                                  let distance = SqlFunctions.SquareRoot(Math.Pow(69.1 * (r.Id), 2) + Math.Pow(69.1 * (r.Id), 2) * SqlFunctions.Cos((double?)r.Id / 57.3))
    
                                  where distance > 10
    
                                  select distance).FirstOrDefault();
    
                    Console.WriteLine(result); 
    

    The result:

    I useEntity Framework 5, .Net 4.5, VS2012.

    And For downloading Entity Framework 5 or higher:

    https://www.nuget.org/packages/EntityFramework/

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, October 24, 2013 2:33 AM
    Moderator