Skip to Main Content

ODP.NET

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

EF Core 2.2 + Oracle.ManagedDataAccess.Core 2.19.31 - Descending sort order, NULLS LAST?

3663071Oct 4 2019 — edited Oct 15 2019

This one has been stumping me for a while, not sure there is a fix after the research I've already done.

Problem:
I have an Oracle 12C DB table with the following DDL:

CREATE TABLE TEST_TABLE

(

  ID NUMBER(10, 0) NOT NULL

, STRINGCOL VARCHAR2(50)

, CONSTRAINT TEST_TABLE_PK PRIMARY KEY

  (

    ID

  )

  ENABLE

);

INSERT INTO TEST_TABLE (ID, STRINGCOL) VALUES (1, null);

INSERT INTO TEST_TABLE (ID, STRINGCOL) VALUES (2, 'ZZZZ');

INSERT INTO TEST_TABLE (ID, STRINGCOL) VALUES (3, '1111');

INSERT INTO TEST_TABLE (ID, STRINGCOL) VALUES (4, 'zzzz');

INSERT INTO TEST_TABLE (ID, STRINGCOL) VALUES (5, '9999');

INSERT INTO TEST_TABLE (ID, STRINGCOL) VALUES (6, 'aaaa');

INSERT INTO TEST_TABLE (ID, STRINGCOL) VALUES (7, 'AAAA');

I want to sort this column in either ASC or DESC and have values in this order:

Expected Outcome:

ASCDESC
(null)zzzz
1111aaaa
9999ZZZZ
aaaaAAAA
zzzz9999
AAAA1111
ZZZZ(null)

EF Core 2.2 LINQ expression (Descending sort):

var results = dbContext.TestTables.OrderByDescending(x => x.StringCol).ToList();

SQL Statement constructed:

SELECT "x"."ID", "x"."STRINGCOL"
FROM "TEST_TABLE" "x"
ORDER BY "x"."STRINGCOL" DESC;

Query Results:

STRINGCOL
(null)
zzzz
aaaa
ZZZZ
AAAA
9999
1111

The SQL query I want to achieve is the following:

SELECT "x"."ID", "x"."STRINGCOL"

FROM "TEST_TABLE" "x"

ORDER BY "x"."STRINGCOL" DESC NULLS LAST

FETCH NEXT 20 ROWS ONLY;

Query Results:

STRINGCOL
zzzz
aaaa
ZZZZ
AAAA
9999
1111
(null)

I've tried a number of LINQ expressions, and have come up empty on getting the generated SQL query to properly allow this type of sorting.  Seems like many others would want this same thing, am I missing something here?

EF Core 2.2 LINQ expression (Descending sort):

var results = dbContext.TestTables.OrderByDescending(x => !string.IsNullOrEmpty(x.StringCol)).ThenByDescending(x => x.StringCol).ToList();

Generated Query:

SELECT "x"."ID", "x"."STRINGCOL"

FROM "TEST_TABLE" "x"

ORDER BY CASE

    WHEN "x"."STRINGCOL" IS NOT NULL AND ("x"."STRINGCOL" <> N'')

    THEN 1 ELSE 0

END DESC, "x"."STRINGCOL" DESC;

Query Results:

STRINGCOL
(null)
zzzz
aaaa
ZZZZ
AAAA
9999
1111
This post has been answered by 3663071 on Oct 14 2019
Jump to Answer
Comments
Post Details
Added on Oct 4 2019
3 comments
1,038 views