2009-10-02 51 views
0

我有了這個功能Ado.net實體條.include()方法不工作

public static AdoEntity.Inspector GetInspectorWithInclude(int id, List<string> properties) 
    { 
     using (var context = new Inspection09Entities()) 
     { 
      var query = context.Inspector; 
      if (properties != null) 
      { 
       foreach (var prop in properties) 
       { 
        if (!string.IsNullOrEmpty(prop)) 
         query.Include(prop); 
       } 
      } 
      return query.Where(i => i.ID == id).First(); 
     } 
    } 

,我用它來讓我從數據庫和一個額外的功能。「檢查員」指定爲「包含」什麼與數據。所以它需要一個列表<'string'>並將它們包含在查詢中。這個函數似乎不起作用,因爲返回的對象仍然不包含請求的數據。有人能告訴我這種方法/方法有什麼問題嗎?

在此先感謝。

解決方案

謝謝米莎N.的建議,我已經孵出它擴展了的ObjectQuery類此EF幫手。希望其他人可能會覺得它有用。

/// <summary> 
/// The include extesion that takes a list and returns a object query with the included data. 
/// </summary> 
/// <param name="objectQuery"> 
/// The object query. 
/// </param> 
/// <param name="includes"> 
/// The list of strings to include. 
/// </param> 
/// <typeparam name="T"> 
/// </typeparam> 
/// <returns> 
/// An object query of T type with the included data. 
/// </returns> 
public static ObjectQuery<T> Include<T>(this ObjectQuery<T> objectQuery, List<string> includes) 
{ 
    ObjectQuery<T> query = objectQuery; 
    if (includes != null) includes.ForEach(s => { if (!string.IsNullOrEmpty(s)) query = query.Include(s); }); 

    return query; 
} 

用法示例。

using(var context = new MyEntity()) 
{ 
    var includes = new List<string> 
    { 
     "Address", 
     "Orders", 
     "Invoices" 
    } 
    return context.CustomerSet.Include(includes).First(c => c.ID == customerID); 
} 

回答

3

沒有什麼錯你的方法,只是一個小東西需要改變:

public static AdoEntity.Inspector GetInspectorWithInclude(int id, List<string> properties) 
{ 
    using (var context = new Inspection09Entities()) 
    { 
     var query = context.Inspector; 
     if (properties != null) 
     { 
      foreach (var prop in properties) 
      { 
       if (!string.IsNullOrEmpty(prop)) 
        query = query.Include(prop);// <--- HERE 
      } 
     } 
     return query.Where(i => i.ID == id).First(); 
    } 
} 

ObjectQuery.Include()方法將返回改變的ObjectQuery對象,你有沒有做改變初始查詢。

希望這有助於