I've gone down a bit of a rabbit hole trying to execute a window function in Entity Framework. (The project in question is built on EF but would gain a lot from calculating PERCENTILE_DISC on the SQL Server.)
I'm creating a new Convention and adding it to the object model to translate calls to a certain method into SQL that executes the PERCENT_DISC window function.
The created EdmFunction has a CommandText of:
PERCENTILE_DISC (0.8) WITHIN GROUP (ORDER BY o.ExpectedPayment) OVER (PARTITION BY o.OrderType)
But when I do this to execute the function:
var medians = context.Set<UserLocation>().Select(x => CustomFunction.Percentile()).ToList();
This throws an EntityCommandCompilationException with the following message:
System.Data.Entity.Core.EntityCommandCompilationException:
'An error occurred while preparing definition of the function 'ConsoleApp5.Percentile'. See the inner exception for details.'
Inner Exception:
EntitySqlException: The query syntax is not valid. Near identifier 'WITHIN', line 1, column 35.
Yet this direct query gets the expected results:
var p80s = context.Database.SqlQuery<decimal>("SELECT DISTINCT PERCENTILE_DISC (0.8) WITHIN GROUP (ORDER BY o.ExpectedPayment) OVER (PARTITION BY o.OrderType) from Orders o").ToList();
I suspect that this is due to the EF parser not being built to handle window functions. So, I'd like to be able to override that EntityCommandCompilationException and have EF try to execute the query anyhow. Failing that, I'd like to at least see the SQL generated so far to see if there's a different problem causing genuinely invalid SQL. How can I accomplish either of these?