I’m having difficuly mapping a simple T-SQL query such as this
select min(price) as MinPrice, max(price) as MaxPrice, avg(price) as AvgPrice
from titles
to a Linq Expression such as this:
var answer = from t in Titles
select new { MinPrice=Min(t.Price), MaxPrice=Max(t.Price), AvgPrice=Avg(t.Price)};
Obviously this doesn’t work since Min doesn’t exisit in this context. I also understand that some sort of Group clause is required, but since I don’t have a group by in the original T-Sql statement I’m not sure how a group by in this linq query would apply.
I’m using EF 4, but in this case, I doubt that should matter in this example.
Not sure it works with EF, but you could try something like that :
EDIT: just tried in LINQPad with Linq to SQL, it works… so it probably works in EF too
The query above generates the following SQL:
(the
SELECT TOP(1)part is only there because of the call toFirst)This is apparently not optimal, but I assume SQL Server is clever enough to optimize it to something simpler…