实体框架Include()强类型

时间:2011-05-23 20:54:02

标签: c# asp.net entity-framework

有没有办法使用System.Data.Entity.Include方法进行强类型化?在下面的方法中,Escalation是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();
}

2 个答案:

答案 0 :(得分:94)

这已在Entity Framework 4.1中提供。

有关如何使用包含功能的参考信息,请参阅此处,还会显示如何包含多个级别:http://msdn.microsoft.com/en-us/library/gg671236(VS.103).aspx

强类型Include()方法是一种扩展方法,因此您必须记住声明using System.Data.Entity;语句。

答案 1 :(得分:7)

信用转到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)