LINQ to Entities does not recognize the method 'Double Parse(System.String)' cannot be translated into a store expression C# asp.net

I try to order Departments by number, but since the departement number stored as a string in database, I can’t just use Order by number.
I try to parse it as float but it did not work. Then I tried to parse it as Double. That does not work either. Any suggestions? The following is my code.

using (var db = new Context())
{
    var datasource = (from x in db.Departments 
                      orderby double.Parse(x.DepartmentNumber) 
                      select x).ToList();
    lvData.DataSource = datasource;
    lvData.DataBind();
}

Thanks for the answer, I did the following, but the results are not entirly correct.

 var datasource = (from x in db.Departments orderby x.DepartmentNumber select x).ToList().OrderBy(Department => float.Parse(Department.DepartmentNumber));

enter image description here

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

One solution it would be the following:

var datasource = db.Departments 
                   .ToList()
                   .OrderBy(department => double.Parse(department.DepartmentNumber));

You fetch all the data from the database in the memory of your application (by calling ToList, which requests the immediate execution of the query.) and then you make the ordering in memory.

The reason why the query below doesn’t work:

var datasource = (from x in db.Departments 
                  orderby double.Parse(x.DepartmentNumber) 
                  select x).ToList();

is the fact that double.Parse cannot be translated to an equivalent function in sql and then the whole sql query be submitted to the database for execution.

Solution 2

Actually the following solved the problem and provided the required results:

 var datasource = (from x in db.Departments orderby x.DepartmentNumber select x).ToList().OrderBy(Department => Convert.ToDouble(Department.DepartmentNumber, System.Globalization.CultureInfo.InvariantCulture));

enter image description here

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply