实体框架Include()强类型

Kyl*_*ers 52 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();
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*inF 95

这已在Entity Framework 4.1中提供.

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

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

  • 这应该标记为正确的答案.特别是对于那些习惯于ReSharper建议使用```using```语句的人来说,我们忘记了我们需要不时手动添加一个. (4认同)
  • 缺少 using 语句是什么让我。感谢您的提醒。 (2认同)

Nat*_*lor 7

幸得乔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;
  }
}
Run Code Online (Sandbox Code Playgroud)
ctx.Users.Include(u => u.Order.Item)
Run Code Online (Sandbox Code Playgroud)

  • 该逻辑已包含在System.Data.Entity命名空间中.您可以使用Include with Expression <Func <TSource,TProperty >>.请注意,Escalation是ICollection <Escalation>. (12认同)