3

I'm not sure if this has been answered yet, I looked at a couple of questions but I don't think they were quite what I was after.

Let's say I have 3 tables:

Restaurant 1.....M MenuCategory 1.....M MenuItem

I have a L2E query that looks something like this:

Restaurant = context.Restaurant
   .Include(r => r.MenuCategory)
   .FirstOrDefault(r => r.RestaurantId == resaurantId);

Which works to some extent, but it only pre-loads the menu categories.

As a work around I am able to iterate around each category and call .Load() on them, but this will involve hitting a lot more that in theory I should need to.

What I really want to be able to do is something like:

Restaurant = context.Restaurant
   .Include(r => r.MenuCategory)
   .Include(r => r.MenuCategory.MenuItems)
   .FirstOrDefault(r => r.RestaurantId == resaurantId);

But clearly this isn't available as r.MenuCategory is an enumerable

ANSWER 1:

context.Restaurant.Include("MenuCategory.MenuItems");

  • This works, but it is not strongly typed. I wonder if anyone is able to come up with a second answer that is strongly typed (I may move this to another question as this has been answered, and answered well.

I have moved this to another question as I felt it was unfair to take away from an answer that is perfect and works exactly as it should:

Entity Framework - Include in sub query? - Part 2

2 Answers 2

7

You can still use the Strongly typed version to do it. Just use:

    Restaurant = context.Restaurant
    .Include(r => r.MenuCategory.Select(m => m.MenuItems))
    .FirstOrDefault(r => r.RestaurantId == resaurantId);
Sign up to request clarification or add additional context in comments.

Comments

2

This link here seems to resolve your problem ?

var result = context.Restaurant.Include("MenuCategory.MenuItems");

2 Comments

Well done - this sorted the issue for me....but, I really don't like this untyped approach, which is why I'd used an extension method. I will put the extension method in the question - just wonder if anyone is able to come up with a typed solution
I have setup a part 2 to this question here, stackoverflow.com/questions/1663783/…, if you're interested

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.