2013-10-21 47 views
0

我從實體框架中獲取此實體: Parent,Child,GrandChild和等效實體ParentModel和ChildModel。將IQueryable轉換爲嵌套集合中的IList

簡體:

class ParentModel 
{ 
    public IList<ChildModel> Children { get; set; } 
} 

class ChildModel 
{ 
    public string GrandChild { get; set; } 
} 

在父擴展我有方法 「ToModel」

public static IEnumerable<ProductCategoryModel> ToModel(
    this IQueryable<ProductCategory> query) 
{ 
    IList<ParentModel> model = 
     query.Select(p => new ParentModel { 
          Childs = p.Childs.Select(ch => new ChildModel { 
               Grandchild = ch.Grandchild.Code 
               }).ToList() 
        }).ToList(); 

    return model; 
} 

問題是,這是行不通的。 我知道爲什麼 - 嵌套的ToList()方法不能在數據庫端運行。

是否有任何簡單的解決方案如何編寫正確的等效代碼將工作OK,會很簡單?我看到了一些foreach的解決方案,但在我看來,它不會很好。

+0

「它不工作」 沒有按」我們可以告訴我們發生了什麼。你有例外嗎?它是否給出空的結果?還有別的嗎? –

回答

0

你會分兩步工作:

  1. 獲取數據,你想
  2. 它帶入的形式,你想
public static IEnumerable<ProductCategoryModel> ToModel(
    this IQueryable<ProductCategory> query) 
{ 
    return query.Select(p => new 
         { 
          Children = p.Childs 
             .Select(ch => new ChildModel() 
               { 
               Grandchild = ch.Grandchild.Code 
               }) 
         }) 
       .AsEnumerable() 
       .Select(x => new ParentModel { Children = x.Children.ToList() }) 
       .ToList(); 
}