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.
Take(1)
before aFirstOrDefault
is kinda pointless.OrderByDescending(n => n.RawValue.PadLeft(10,' '))
? (Just curious whether EF can translate pad left to be a server side op or not)