LINQ to Entities does not recognize the method ‘Double Parse(System.String)’ method, and this method cannot be translated into a store expression

The problem here is that your query is being translated into SQL and run on the database, and Entity Framework doesn’t know how to translate Double.Parse into valid SQL code. However, you can define a custom method to do the parsing, and tell Entity Framework how to translate that method to SQL. Here’s how it goes:

Define the translation

Open up your *.edmx file in a text editor, and look for the <edmx:ConceptualModels> tag. Under that you should see a <Schema Namespace="YourModel" ...> tag. Inside the Schema tag, add the following:

    <Function Name="ParseDouble" ReturnType="Edm.Double"> 
        <Parameter Name="stringvalue" Type="Edm.String" /> 
        <DefiningExpression> 
            cast(stringvalue as Edm.Double)
        </DefiningExpression> 
    </Function>

This defines the Enity-SQL code that your custom ParseDouble function is going to be translated into.

Create a method to be translated

Now we need to define a matching function in code that you can put in your LINQ statement. Your EDMX file is used to generate a partial class that inherits from ObjectContext. Since it’s a partial class, you can add your own methods to it without touching the generated code – just make sure the class names match.

using System.Data.Objects.DataClasses;

public partial class YourObjectContext
{
    /// <summary>
    ///     This method exists for use in LINQ queries,
    ///     as a stub that will be converted to a SQL CAST statement.
    /// </summary>
    [EdmFunction("YourModel", "ParseDouble")]
    public static double ParseDouble(string stringvalue)
    {
        return Double.Parse(stringvalue);
    }
}

Now you can go back to your LINQ statement, and replace any instances of Double.Parse with YourObjectContext.ParseDouble. Since this is an actual method that actually calls Double.Parse, it will work on LINQ to Objects calls, and since it is also defined in the EDMX file, it can be translated into SQL by LINQ to Entities as well.

But wait, you’re not done yet!

I noticed that your LINQ statement also includes a call to Math.Round. I don’t know off the top of my head if Entity Framework includes a translation for that method, but if it doesn’t, you’ll get the same error for that method after you fix the one for Double.Parse. Fortunately, the solution for that case is almost exactly the same, except the function defined in the EDMX file would look something like this:

    <Function Name="Round" ReturnType="Edm.Double"> 
        <Parameter Name="input" Type="Edm.Double" /> 
        <DefiningExpression> 
            Round(input)
        </DefiningExpression> 
    </Function>

You can use this list of EDM Canonical Functions to see what’s valid to put inside the <DefiningExpression> tags.

Leave a Comment