Class Customer has the following method, which returns an IQueryable with the linq query to get the active sales for a customer:
public IQueryable<SalesHeader> QueryCurrentSales()
{
// this.SalesHeaders is an association defined in the DBML between
// the Customer and SalesHeader tables (SalesHeader.CustomerId <-> Customer.Id).
return this.SalesHeaders
.Where(sh => sh.Status == 1).AsQueryable();
}
The idea is to centralise the query definition in a single point, so that later we can get the SalesHeader rows, do a count, paginate using the PaginatedList class (from NerdsDinner), and add further Where conditions when searching Sales within active SalesHeaders.
However, after running the SQL Sever profiler, I’ve discovered that doing the following, gets all the rows and then does the Count in memory.
// cust is an object of type Customer.
int rows = cust.QueryCurrentSales().count();
I guess that the problem lies in the fact that we have used the AsQueryable() method, but I don’t know what would be the correct way to accomplish what we intended.
You haven’t shown what
SalesHeadersis. The fact that you feel you need to doAsQueryablesuggests that it’s returning anIEnumerable<T>rather than anIQueryable<T>… which is probably the problem. If you could showSalesHeaders, we may be able to help.It’s possible that instead of using
AsQueryableyou may be able to just cast toIQueryable<SalesHaeder>if theSalesHeadersproperty is returning an expression which could actually be returned asIQueryable<SalesHeaders>in the first place – but in that case I’d suggest changing the property type instead.EDIT: Okay, if it’s an entity set then that’s probably tricky to fix directly.
I know it’s ugly, but how about something like:
Here I’m assuming you have some way of getting to the data context in question – I can’t remember offhand whether there’s an easy way of doing this in LINQ to SQL, but I’d expect so.