Entity Framework Include()强类型化

54

使用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();
}

如果您使用EFv4.1,则无需使用魔术字符串:https://dev59.com/-FXTa4cB1Zd3GeqPxwz3#5247423 - Ladislav Mrnka
这也可能会引起您的兴趣:https://dev59.com/8m435IYBdhLWcg3whASx#5376637 - Ladislav Mrnka
2个回答

100

这在Entity Framework 4.1中已经可用。

查看此处有关如何使用include功能的参考,它还展示了如何包含多个级别:http://msdn.microsoft.com/zh-cn/library/gg671236(VS.103).aspx

强类型Include()方法是一个扩展方法,因此您需要记得声明using System.Data.Entity;语句。


4
应将此标记为正确答案。特别是对于那些习惯于使用 ReSharper 建议 using 语句的人而言,我们会忘记需要不时手动添加一个。 - gligoran
2
缺失的using语句是让我困扰的原因。感谢您的提醒。 - BrianLegg
有没有理由不使用这个扩展(或者反过来:有没有理由使用带有string参数的include)? - Michel

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)

13
该逻辑已包含在System.Data.Entity命名空间中。您可以使用带有Expression<Func<TSource,TProperty>>的Include方法。请注意上面提到的Escalation是一个ICollection<Escalation>。 - user342706

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接