Entity Framework - Include in sub query?

2019-04-11 17:25发布

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条回答
做自己的国王
2楼-- · 2019-04-11 17:51

This link here seems to resolve your problem ?

var result = context.Restaurant.Include("MenuCategory.MenuItems");
查看更多
Bombasti
3楼-- · 2019-04-11 17:57

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);
查看更多
登录 后发表回答