Entity Framework Include() strongly typed

后端 未结 2 1222
闹比i
闹比i 2020-12-05 17:17

Is there a way to make this strongly typed using the System.Data.Entity.Include method? In the method below Escalation is a ICollection<>.

public IEnumer         


        
相关标签:
2条回答
  • 2020-12-05 17:22

    This is already available in 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

    The strongly typed Include() method is an extension method so you have to remember to declare the using System.Data.Entity; statement.

    0 讨论(0)
  • 2020-12-05 17:35

    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)
    
    0 讨论(0)
提交回复
热议问题