2015-12-22 191 views
0

嗨我想要使用該代碼來獲取包含用戶的客戶的屬性User.Email。但它的一個對象(用戶類型用戶),所以它引發異常。我應該修補什麼?獲取內部對象的屬性

public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string SortField, bool Ascending) 
    { 
     if (!string.IsNullOrWhiteSpace(SortField)) 
     { 
      var param = Expression.Parameter(typeof (T), "p"); 
      var prop = Expression.Property(param, SortField); 
      var exp = Expression.Lambda(prop, param); 
      string method = Ascending ? "OrderBy" : "OrderByDescending"; 
      Type[] types = new Type[] {q.ElementType, exp.Body.Type}; 
      var mce = Expression.Call(typeof (Queryable), method, types, q.Expression, exp); 
      return q.Provider.CreateQuery<T>(mce); 
     } 
     else 
     { 
      return q; 
     } 
    } 

回答

0

你需要傳遞一個屬性路徑功能(如 「User.Email」),佔這裏面,像這樣

public static IQueryable<T> OrderByField<T>(this IQueryable<T> source, string sortField, bool ascending) 
{ 
    if (string.IsNullOrWhiteSpace(sortField)) return source; 
    var item = Expression.Parameter(typeof(T), "item"); 
    Expression member = null; 
    foreach (var memberName in sortField.Split('.')) 
     member = Expression.PropertyOrField(member ?? item, memberName); 
    var selector = Expression.Lambda(member, item); 
    var method = ascending ? "OrderBy" : "OrderByDescending"; 
    var types = new [] { source.ElementType, selector.Body.Type }; 
    var expression = Expression.Call(typeof(Queryable), method, types, source.Expression, selector); 
    return source.Provider.CreateQuery<T>(expression); 
} 

的重要組成部分是

var item = Expression.Parameter(typeof(T), "item"); 
    Expression member = null; 
    foreach (var memberName in sortField.Split('.')) 
     member = Expression.PropertyOrField(member ?? item, memberName); 

它從expression參數開始,爲路徑中指定的每個成員構建一個訪問器。