7

I am trying to eager load properties of a derived class in an Entity Framework model.

I read all over the place that I have to first filter the set with OfType() before including properties with Include():

var persons = Context.Persons
                     .OfType<Employee>()
                     .Include("Compensation")

I don't know how to get that Include() to work though because in my case, Persons is a DbSet, OfType() returns an IQueryable and IQueryable does not define an Include() method.

1

1 Answer 1

16

Place this:

using System.Data.Entity;

into your using's list, and after that you will be able to use Include extension methods family from DbExtensions class:

    public static IQueryable<T> Include<T, TProperty>(this IQueryable<T> source, Expression<Func<T, TProperty>> path) where T : class;
    public static IQueryable<T> Include<T>(this IQueryable<T> source, string path) where T : class;
    public static IQueryable Include(this IQueryable source, string path);

They accept IQueryable as the first argument, and there are strongly-typed ones, too, which is better, then Include(String).

5
  • 2
    Ah! Thanks, I thought it was probably an extension method. I really wish that VS made the namespace discoverable and/or that people included the usings in their samples :) Aug 23, 2012 at 6:08
  • @XavierPoinas: completely agree with you, this confused me too first time.
    – Dennis
    Aug 23, 2012 at 6:15
  • @XavierPoinas I've been converted to Resharper for this (amongst other) reasons. Resharper will suggest extension methods to fill this missing gap in Visual Studios suggestions in intellisense. Totally agree with you! Aug 25, 2015 at 18:24
  • 1
    @TheSenator Actually VS 2015 now does that too so I'm pretty happy now :-) Aug 27, 2015 at 6:20
  • @XavierPoinas: true. Ultimately, VS will kill R#. :)
    – Dennis
    Aug 27, 2015 at 6:22

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.