Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This question is a bit old, but here are two EF-independent solutions if you or anyone else is still looking:</p> <p><strong>1. Reflection-based Solution</strong></p> <p>This solution is what the .NET Framework falls back to if the <code>IQueryable</code> does not cast to a <code>DbQuery</code> or <code>ObjectQuery</code>. Skip these casts (and the efficiency it provides) and you've decoupled the solution from Entity Framework.</p> <pre><code>public static class IncludeExtension { private static T QueryInclude&lt;T&gt;(T query, string path) { MethodInfo includeMethod = query.GetType().GetMethod("Include", new Type[] { typeof(string) }); if ((includeMethod != null) &amp;&amp; typeof(T).IsAssignableFrom(includeMethod.ReturnType)) { return (T)includeMethod.Invoke(query, new object[] { path }); } return query; } public static IQueryable&lt;T&gt; Include&lt;T&gt;(this IQueryable&lt;T&gt; query, string path) where T : class { return QueryInclude(query, path); } // Add other Include overloads. } </code></pre> <p><strong>2. Dyanmics-based Solution</strong></p> <p>Here the <code>QueryInclude&lt;T&gt;</code> method uses the <code>dynamic</code> type to avoid reflection.</p> <pre><code>public static class IncludeExtension { private static T QueryInclude&lt;T&gt;(T query, string path) { dynamic querytWithIncludeMethod = query as dynamic; try { return (T)querytWithIncludeMethod.Include(path); } catch (RuntimeBinderException) { return query; } } public static IQueryable&lt;T&gt; Include&lt;T&gt;(this IQueryable&lt;T&gt; query, string path) where T : class { return QueryInclude(query, path); } // Add other Include overloads. } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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