Reputation: 373
Lets say that I have a class called Stock and which has a virtual ICollection Prices, which is a historical set of prices.
If you fetch a stock and after the stock is materialized you query the Prices but apply a filter like mystock.Prices.OrderByDescending(px => px.Date).First(), EF internally loads all the prices and then it applies the filters used, since prices could be a large collection, I would really like to see EF just load the price that matched my where criteria. Basically applying the filtering at the server end rather than client side.
Is it possible to do this?
Thanks
Upvotes: 2
Views: 928
Reputation:
It's possible, but this way only works if you can assume Prices
is really an EntityCollection
rather than some other class that also happens to implement ICollection
. I'm not sure if this is true in all supported EF scenarios. The function to use is EntityCollection
's CreateSourceQuery
function.
((EntityCollection<Price>)stock.Prices).CreateSourceQuery().OrderByDescending(price => price.Date).First();
If that doesn't work for you, another possibility might be to go back to the context, and query from there:
(from price in context.Prices
where price.StockId == stockId
orderby price.Date descending
select price).First();
Upvotes: 2