A: 

Try adding another repository method that looks like this:

public int CommunitiesCount()
{
    get { return _ctx.Communities.Count(); }
}

This will allow you to return a count without exposing the entire object tree to the user, which is what I think you're trying to do anyway.

As you may have already guessed, I suspect that what you are calling the anonymous types are at fault (they're not really anonymous types; they are actual objects, which you are apparently partially populating in an effort to hide some of the fields from the end user).

Robert Harvey
@Robert,I'm not sure if the Count() method itself is the culprit. When I do a cr.Communities, I'm expecting a fully hydrated IQueryable collection. mr.Markets.Count() and sr.States.Count() return the expected results.
Praveen
Did this particular rendition of count() work?
Robert Harvey
Yes, _ctx.Communities.Count() gives me the right count. However, I'm looking for communityRepository.Communities, an IQueryable<Model.Community> list.
Praveen
+1  A: 

These are non-hydrated queries, not fully-hydrated collections.

The Communities query differs from the other two because it calls methods as objects are hydrated. These method calls are not translatable to SQL.


Normally this isn't a problem. For example: if you say Communities.ToList(), it will work and the methods will be called from the objects as they are hydrated.

If you modify the query such that the objects aren't hydrated, for example: when you say Communities.Count(), linq to sql attempts to send the method calls into the database and throws since it cannot. It does this even though those method calls ultimately would not affect the resulting count.


The simplest fix (if you truly expect fully hydrated collections) is to add ToList to the community query, hydrating it.

David B
That did it. It doesn't fire the query until you call a method on IQueryable?
Praveen
Most Linq methods are deferred - they do not evaluate the query until the result is enumerated. foreach and ToList are both means to enumerate a query.
David B