I have a custom CLR Aggregate function on SQL Server to calculate percentiles. Is it possible to call my custom aggregate function through Entity Framework? How is the mapping configured to allow this?
I have tried using codefirstfunctions similar to what is described on Entity Framework 6 Code First Custom Functions, however the functions seem to only be allowed to take scaler parameters, where my function is an aggregate function so will need to take a list of items (similar to how Sum, Averagg and Count work).
The Aggregate functions has the following signature, taking in the value we want the median from and the percentile (50 is median, 25 lower quartile, 75 upper quartile)
CREATE AGGREGATE [dbo].[Percentile]
(@value [float], @tile [smallint])
RETURNS[float]
EXTERNAL NAME [SqlFuncs].[Percentile]
GO
I have tried adding a DbFunctionAttribute, but not entirely sure how to hook it up to entity framework store model using code first.
[DbFunction("SqlServer", "Percentile")]
public static double? Percentile(IEnumerable<int?> arg, int tile)
{
throw new NotSupportedException("Direct calls are not supported.");
}
What I am looking for is to be able to write something like
paymentsTable
.GroupBy(x=>x.CustomerId)
.Select(new{
Median = MyDbContext.Percentile(x.Select(g=>g.Amount), 50)
});
Which will map to SQL like
SELECT [dbo].[Percentile](Amount, 50) as Median
FROM Payments
GROUP BY CustomerId