【问题标题】:Entity Framework Include() strongly typed实体框架 Include() 强类型
【发布时间】:2011-08-31 11:14:04
【问题描述】:

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

【问题讨论】:

标签: c# asp.net entity-framework


【解决方案1】:

这在 Entity Framework 4.1 中已经可用。

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

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

【讨论】:

  • 这应该被标记为正确答案。特别是对于我们这些习惯于 ReSharper 建议 using 语句的人来说,我们忘记了我们需要不时手动添加一个。
  • 缺失的 using 语句让我着迷。谢谢提醒。
  • 是否应该有理由不使用此扩展程序(或相反:是否有理由将includestring 参数一起使用)?
【解决方案2】:

感谢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)

【讨论】:

  • 该逻辑已包含在 System.Data.Entity 命名空间中。您可以将 Include 与 Expression> 一起使用。请注意上面的升级是一个 ICollection.
猜你喜欢
  • 1970-01-01
  • 2016-11-27
  • 2013-09-13
  • 1970-01-01
  • 1970-01-01
  • 2017-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多