How to use greatest() function in EF core LINQ queries

Mohit Tyagi 1 Reputation point
2021-06-22T13:39:21.11+00:00

Azure SQL now supports greatest() function to find out the greatest value among multiple columns thereby preventing from writing cumbersome CASE WHEN statements in the query.
Ref: https://learn.microsoft.com/en-us/sql/t-sql/functions/logical-functions-greatest-transact-sql?view=sql-server-ver15#syntax

I need to use this in a LINQ query's order by clause. I have 4 date columns and I need to order the results based on the maximum of these. Can someone please point me how can this be achieved? cc: @Duane Arnold

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
698 questions
Azure SQL Database
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,315 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,621 Reputation points
    2021-06-23T02:26:19.627+00:00

    Hi MohitTyagi-2522,
    As AgaveJoe said that EF Core does not support greatest() function.
    And you can use Max method to get the maximum resulting value.
    Here is also a related thread you can refer to.
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. GrzegorzF 1 Reputation point
    2022-05-30T14:55:08.703+00:00

    I know question was asked a year ago. However, since EF core 2, there is DbFunctionAttribute, which allows you to define custom non-aggregate db functions to use with linq.

    [DbFunction("array_percentile")]
            public static double ArrayPercentile(double[] values, double fraction)
            {
                throw new Exception();
            }
    

    Postgres supports array types. You can use it as follows:

    var percentiles_context.MyTable.Select(x => ArrayPercentile(x.ArrayColumn, 0.9)).ToList();
    

    Probably it will work with params as well, but you can also try array approach or fixed number of arguments

    Regards GrzegorzF

    0 comments No comments