Skip to content

Query: Order by with condition evaluating to true/false produces invalid SQL #8092

@slubowsky

Description

@slubowsky

Putting a condition inside an order by is causing invalid SQL. I think I see similar issues but the ones I found were closed months ago and any fixes should be present in version 1.1.1 which is the version I am using so opening this in case its not a duplicate

var values = await _values 
                .OrderBy(f =>  search.Field == "code" ? f.Code : f.Description)
                .Skip((currentPage - 1) * currentPageSize)
                .Take(currentPageSize)
                .ProjectTo<TV>()
                .ToListAsync();

Generates:

SELECT [t].[StartDate], [t].[EndDate], [t].[Id], [t].[Code], [t].[Description]
FROM (
    SELECT [f0].*
    FROM [AssessmentType] AS [f0]
    ORDER BY CASE
        WHEN 0
        THEN [f0].[Code] ELSE [f0].[Description]
    END
    OFFSET @__p_1 ROWS FETCH NEXT @__p_2 ROWS ONLY
) AS [t]

Results in

Microsoft.EntityFrameworkCore.Query.Internal.SqlServerQueryCompilationContextFactory:Error: An exception occurred in the database while iterating the results of a query.
System.Data.SqlClient.SqlException: An expression of non-boolean type specified in a context where a condition is expected, near 'THEN'.
Incorrect syntax near 'OFFSET'.
Invalid usage of the option NEXT in the FETCH statement.
   at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__107_0(Task`1 result)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
...

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions