Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - Include in sub query?

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

like image 595
Paul Avatar asked Nov 24 '25 08:11

Paul


1 Answers

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);
like image 65
Jack Woodward Avatar answered Nov 26 '25 22:11

Jack Woodward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!