This error occurs when attempting to run a LINQ expression containing a method that is not supported by the database engine for Entity Framework. In this case, the method causing the error is Double.Parse(string).
In the provided code, the error is encountered in the following statement:
model.Referring = Math.Round(_newSurveyResult.Select(m => string.IsNullOrEmpty(m.Question1) ? 0 : Double.Parse(m.Question1)).Average());
Entity Framework translates LINQ expressions into SQL queries to execute on the database. However, the Double.Parse method is not a standard SQL function and cannot be directly converted to SQL.
To resolve this issue, you can define a custom function in your Entity Framework model that can be translated into the equivalent SQL expression. In this case, we will define a function called ParseDouble.
Open the *.edmx file for your model and locate the
<Function Name="ParseDouble" ReturnType="Edm.Double"> <Parameter Name="stringvalue" Type="Edm.String" /> <DefiningExpression> cast(stringvalue as Edm.Double) </DefiningExpression> </Function>
Next, create a partial class for your ObjectContext class and add the following method to it:
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); } }
Once you have defined and implemented the custom function, you can update your LINQ expression to use it:
model.Referring = Math.Round(_newSurveyResult.Select(m => string.IsNullOrEmpty(m.Question1) ? 0 : YourObjectContext.ParseDouble(m.Question1)).Average());
Now, the LINQ expression should be successfully translated into a SQL query that can be executed by the database engine.
The above is the detailed content of How to Resolve the 'LINQ to Entities does not recognize the method 'Double.Parse'' Error?. For more information, please follow other related articles on the PHP Chinese website!