29

Attempting to cutover our EF4 solution to EF CTP5, and ran into a problem.

Here's the relevant portion of the model:

enter image description here

The pertinent relationship: - A single County has many Cities - A single City has a single State

Now, i want to perform the following query: - Get all Counties in the system, and include all the Cities, and all the State's for those Cities.

In EF4, i would do this:

var query = ctx.Counties.Include("Cities.State");

In EF CTP5, we have a strongly typed Include, which takes an Expression<Func<TModel,TProperty>>.

I can get all the Cities for the County no problem:

var query = ctx.Counties.Include(x => x.Cities);

But how can i get the State for those Cities too?

I am using pure POCO's, so County.Cities is an ICollection<City>, therefore i cannot do this:

var query = ctx.Counties.Include(x => x.Cities.State)

As ICollection<City> does not have a property called State.

It's almost like i need to use a nested IQueryable.

Any ideas? Do i need to fallback to the magic string Include in this scenario?

RPM1984
  • 72,246
  • 58
  • 225
  • 350

1 Answers1

52

For that you can use you the Select method:

var query = ctx.Counties.Include(x => x.Cities.Select(c => c.State))

Here you can find another example.

Community
  • 1
  • 1
Morteza Manavi
  • 33,026
  • 6
  • 100
  • 83
  • clever! trying now...stay tuned. – RPM1984 Jan 27 '11 at 02:49
  • Works great, thanks a bunch man! +1 and accepted. Haven't seen you answering many EF4 questions lately - Ladislav is taking us both down. :) – RPM1984 Jan 27 '11 at 03:03
  • No problem buddy! That's because I'm totally focused on EF Code First questions. I hope you start using it as well, since I still see EDMX file on your question :) – Morteza Manavi Jan 27 '11 at 03:26
  • Yeah, what can i say - i like having the pretty diagram. :) – RPM1984 Jan 27 '11 at 03:28
  • need your help (if you can). :) See my (related) question - http://stackoverflow.com/questions/5189268/problem-with-eager-loading-nested-navigation-based-on-abstract-entity-ef-ctp5 – RPM1984 Mar 04 '11 at 03:40