Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use a CASE statement with OrderBy in an LINQ to Entities query?

I'm wonder if someone can transform the SQL below to a LINQ to Entities query

SELECT Name, IsEmployee, IsQualityNetwork
FROM Person
ORDER BY CASE WHEN IsQualityNetwork = 1 or IsEmployee = 1 THEN 0 ELSE 1 END, Name

I tried using Linq Dynamic but when this code is executed:

var p = ctx.People
    .OrderBy("CASE WHEN IsQualityNetwork = 1 or IsEmployee = 1 THEN 0 ELSE 1 END")
    .OrderBy(e => e.Name);

I get the exception: {"No property or field 'CASE' exists in type 'Person'"}

like image 897
Michel Fornaris Avatar asked Jun 17 '13 16:06

Michel Fornaris


People also ask

Which entities can LINQ use to perform queries?

LINQ to Entities queries are comprised of LINQ standard query operators (such as Select, Where, and GroupBy) and expressions (x > 10, Contact. LastName, and so on). LINQ operators are not defined by a class, but rather are methods on a class.

Can I use LINQ with Entity Framework?

Entity Framework Core uses Language-Integrated Query (LINQ) to query data from the database. LINQ allows you to use C# (or your . NET language of choice) to write strongly typed queries.

Can we use CASE statement in order by clause in SQL Server?

Nope! Although it is most often used there, CASE is not limited to SELECT statements. For example, you can use it in clauses like IN , WHERE , HAVING , and ORDER BY .


2 Answers

var p = ctx.People.OrderBy(p => (p.IsQualityNetwork == 1 || p.IsEmployee == 1) ? 0 : 1)
                  .ThenBy(p => p.Name);
like image 76
Aducci Avatar answered Oct 18 '22 17:10

Aducci


Here's a translation of your SQL to LINQ.

var query = from p in ctx.People
            let order = p.IsQualityNetwork || p.IsEmployee ? 0 : 1
            orderby order, p.Name
            select new
            {
                p.Name,
                p.IsEmployee,
                p.IsQualityNetwork,
            }

I've used the fluent query syntax so I could show you the let keyword. let allows you to declare a range variable that can then be reused in your query, this can be very useful if you've got a conditional that gets used in a lot of places, or if you need to chain multiple conditionals.

like image 30
Doctor Jones Avatar answered Oct 18 '22 17:10

Doctor Jones