LINQ to Entites: Doing a count over one-to-many relationships

Posted by chris on Stack Overflow See other posts from Stack Overflow or by chris
Published on 2010-04-20T12:40:42Z Indexed on 2010/04/20 12:43 UTC
Read the original article Hit count: 152

I have a couple of tables where there are one to many relationships. Let's say I have a Country table, a State table with a FK to Country, and a City table with a FK to State.

I'd like to be able to create a count of all Cities for a given country, and also a count of cities based on a filter - something like:

foreach( var country in Model.Country ) {
    total = country.State.All().City.All().Count() ;
    filtered = country.State.All().City.Any(c=>c.field == value).Count();
}

Obviously, this doesn't work - is there any way to do this?

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about linq-to-entities