简体   繁体   English

实体框架 Include() 强类型

[英]Entity Framework Include() strongly typed

Is there a way to make this strongly typed using the System.Data.Entity.Include method?有没有办法使用 System.Data.Entity.Include 方法进行强类型化? In the method below Escalation is a ICollection<>.在下面的方法中,升级是一个 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();
}

This is already available in Entity Framework 4.1.这已在 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有关如何使用包含功能的参考,请参见此处,它还显示了如何包含多个级别: 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;强类型的Include()方法是一种扩展方法,因此您必须记住声明using System.Data.Entity; statement.陈述。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM