Note that there are some explanatory texts on larger screens.

plurals
  1. POEntity Framework - Include in sub query? - Part 2
    text
    copied!<p>I'm not sure if this is the right thing to do, I'm sure someone will tell me if it's not.</p> <p>I asked a question (<a href="https://stackoverflow.com/questions/1662760/entity-framework-include-in-sub-query">Entity Framework - Include in sub query?</a>) earlier this evening, which was answered very well and has solved my problem. But, I think there could be a better way, so I'm going to re-ask the question, but slightly differently.</p> <p>Let's say I have 3 tables:</p> <p>Restaurant 1.....M MenuCategory 1.....M MenuItem I have a L2E query that looks something like this:</p> <p>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.</p> <p>What I really want to be able to do is something like:</p> <pre><code>Restaurant = context.Restaurant .Include(r =&gt; r.MenuCategory) .Include(r =&gt; r.MenuCategory.MenuItems) .FirstOrDefault(r =&gt; r.RestaurantId == resaurantId); </code></pre> <p>But clearly this isn't available as r.MenuCategory is an enumerable</p> <p>...the work around is to use the standard notation:</p> <pre><code>context.Restaurant.Include("MenuCategory.MenuItems"); </code></pre> <p>...but this is not strongly typed. This question is about finding a <strong>strongly typed</strong> answer</p> <p>This is the current extension method:</p> <pre><code>public static ObjectQuery&lt;T&gt; Include&lt;T&gt;(this ObjectQuery&lt;T&gt; query, Expression&lt;Func&lt;T, object&gt;&gt; path) { // Retrieve member path: List&lt;PropertyInfo&gt; members = new List&lt;PropertyInfo&gt;(); EntityFrameworkHelper.CollectRelationalMembers(path, members); // Build string path: StringBuilder sb = new StringBuilder(); string separator = ""; foreach (MemberInfo member in members) { sb.Append(separator); sb.Append(member.Name); separator = "."; } // Apply Include: return query.Include(sb.ToString()); } </code></pre> <p>How could this be adapted to allow a strongly typed form of:</p> <pre><code>context.Restaurant.Include("MenuCategory.MenuItems"); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload