EF Core, execute on SQL server order by int cast from string

.net-core c# entity-framework entity-framework-core

Question

I need to find the latest generated item in a SQL table.
Unfortunately for legacy reasons I cannot sort by any other column but a string column (RawValue).
On top of that I cannot sort on this column as string but I need to parse it as Integer.

MyEntity myEntity = await _dbContext.MyEntity
  .AsNoTracking()
  .Where(...) // irrelevant
  .OrderByDescending(n => int.Parse(n.RawValue)).FirstOrDefaultAsync();

Entity Framework generated these warnings which evolve all around the above statement.

Microsoft.EntityFrameworkCore.Query.QueryClientEvaluationWarning" :: The LINQ expression 'orderby Parse([sn].RawValue) desc' could not be translated and will be evaluated locally.

Microsoft.EntityFrameworkCore.Query.QueryClientEvaluationWarning" :: The LINQ expression 'FirstOrDefault()' could not be translated and will be evaluated locally.

How can you execute that on the server side with entity framework?

Model

public class MyEntity
{
    // ctors..

    public int Id { get; private set; }

    [MaxLength(32)]
    public string RawValue { get; private set; }

     // more irrelevant properties..
}

Version information
dotnetcoreapp2.2 EF Core is not directly referenced, but included in <PackageReference Include="Microsoft.AspNetCore.App" />

Solution I just confirmed that Convert.ToInt32(string) does what int.Parse(string) does not. It generates an ORDER BY CONVERT(int, column) .. SQL statement.

1
1
10/27/2019 3:08:53 PM

Accepted Answer

Pretty sure the solution is to use

Convert.ToInt32

Because Int.parse does not have an implementation in the version you are using.

1
10/25/2019 1:55:50 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow