54

Is there a way to make this strongly typed using the System.Data.Entity.Include method? In the method below Escalation is a ICollection<>.

public IEnumerable<EscalationType> GetAllTypes() {
  Database.Configuration.LazyLoadingEnabled = false;
  return Database.EscalationTypes
    .Include("Escalation")
    .Include("Escalation.Primary")
    .Include("Escalation.Backup")
    .Include("Escalation.Primary.ContactInformation")
    .Include("Escalation.Backup.ContactInformation").ToList();
}
  • If you have EFv4.1 you don't have to use magic strings: http://stackoverflow.com/questions/5247324/ef-code-first-ctp5-using-include-method-with-many-to-many-table/5247423#5247423 – Ladislav Mrnka May 23 '11 at 21:21
  • This can also interest you: http://stackoverflow.com/questions/5376421/ef-including-other-entities-generic-repository-pattern/5376637#5376637 – Ladislav Mrnka May 23 '11 at 21:24

2 Answers2

100

This is already available in Entity Framework 4.1.

See here for a reference for how to use the include feature, it also shows how to include multiple levels: http://msdn.microsoft.com/en-us/library/gg671236(VS.103).aspx

The strongly typed Include() method is an extension method so you have to remember to declare the using System.Data.Entity; statement.

Serj Sagan
  • 28,927
  • 17
  • 154
  • 183
MartinF
  • 5,929
  • 5
  • 40
  • 29
  • 4
    This should be marked as the correct answer. Especially for those of us that are so used to ReSharper suggesting ```using``` statements, that we forget that we need to add one manually from time to time. – gligoran Mar 20 '15 at 10:58
  • 2
    The missing using statement was what got me. Thanks for the reminder. – BrianLegg Feb 04 '16 at 20:27
  • Should there be a reason not to use this extension (or the other way around: can there be a reason to use the `include` with the `string` parameter) ? – Michel Aug 26 '16 at 13:39
7

Credit goes to Joe Ferner:

public static class ObjectQueryExtensionMethods {
  public static ObjectQuery<T> Include<T>(this ObjectQuery<T> query, Expression<Func<T, object>> exp) {
    Expression body = exp.Body;
    MemberExpression memberExpression = (MemberExpression)exp.Body;
    string path = GetIncludePath(memberExpression);
    return query.Include(path);
  }

  private static string GetIncludePath(MemberExpression memberExpression) {
    string path = "";
    if (memberExpression.Expression is MemberExpression) {
      path = GetIncludePath((MemberExpression)memberExpression.Expression) + ".";
    }
    PropertyInfo propertyInfo = (PropertyInfo)memberExpression.Member;
    return path + propertyInfo.Name;
  }
}
ctx.Users.Include(u => u.Order.Item)
Nathan Taylor
  • 24,423
  • 19
  • 99
  • 156
  • 13
    That logic is already included in System.Data.Entity namespace. You can use Include with a Expression>. Notice above that Escalation is an ICollection. –  May 23 '11 at 21:09