2014-01-07 56 views
10

我遇到了同樣的問題作爲突破解決here:

然而,得到的答案是不夠的我。首先,我不能在我的生活中找到OData 5.0.0(不是RC1)中的HierarchyNodeExpressionVisitor(或任何地方,嘗試使用Google搜索)。即使我沒有找到它返回IHttpActionResult不夠好

其次,我需要返回一個類型PageResult<MyViewModel>

既定justificiation返回IHttpActionResult是「來處理的事實,結果可能不是一個IQueryable<MyEntity>了「。一旦使用$ expand操作符。

但是這對我來說沒有意義,因爲我認爲$ expand操作符用於在實體上包含導航屬性,就像服務器端Include(e => e.RelatedProperty)一樣。至少在我的情況下,我只包含一個已經在實體上的屬性,所以我不必擔心它「可能是別的東西」。

但是當使用$expand=Department我不能Cast<>()到實體類型,因爲它不能施放SelectAllAndExpand<MyEntity>MyEntity

如何將展開展開回原始實體以便我可以進行投影?

public PageResult<DateSnippetWithDepartmentsViewModel> GetDatesWithDepartments(ODataQueryOptions<DateSnippet> options) 
{ 
    IQueryable query = options.ApplyTo(_context.DateSnippets, new ODataQuerySettings());; 

    //Exception when using $expand.. cannot cast SelectAllAndExpand<DateSnippet> to DateSnippet 
    List<DateSnippet> dateSnippets = query.Cast<DateSnippet>().ToList(); 

    var dateSnippetsViewModels = (from d in dateSnippets 
            select new DateSnippetWithDepartmentsViewModel 
            { 
             ... 
            }); 

    var result = new PageResult<DateSnippetWithDepartmentsViewModel>(
      dateSnippetsViewModels as IEnumerable<DateSnippetWithDepartmentsViewModel>, 
      Request.GetNextPageLink(), 
      Request.GetInlineCount()); 

    return result; 
} 
+0

你不能。你可能想看看這個。 http://beyondtheduck.com/revisting-projecting-and-the-odata-expand-query-option/ – Schandlich

+0

你的DateSnippetWithDepartmentsViewModel和DateSnippets是什麼樣的? –

+1

當你展開一個類型時,你需要有一個虛擬集合(通常是頂層對象中的一個'IEnumberable '或'SingleResult '屬性,然後展開將應用關係foreign_key數據,並且原始對象將擁有它的屬性「擴展「與關係數據 當然,這一切都取決於OData的版本,如果它是一個獨立的或WCF服務實例有時對不同的平臺有不同的規則 – 2014-04-16 21:47:23

回答

1

試試這個。希望應該工作,當我們到達枚舉器時,結果應該是DateSnippet。之前你在做的是試圖在Linq表達式樹中投射。我懷疑在IQueryable執行,這是解決和轉換,而不是轉換。

public PageResult<DateSnippetWithDepartmentsViewModel> GetDatesWithDepartments(ODataQueryOptions<DateSnippet> options) 
{ 
    IQueryable query = options.ApplyTo(_context.DateSnippets, new ODataQuerySettings());; 

    List<DateSnippet> dateSnippets = new List<DateSnippet>(); 
    foreach(DateSnippet item in query) 
    { 
     dateSnippets.Add(item); 
    } 

    var dateSnippetsViewModels = (from d in dateSnippets 
            select new DateSnippetWithDepartmentsViewModel 
            { 
             ... 
            }); 

    var result = new PageResult<DateSnippetWithDepartmentsViewModel>(
      dateSnippetsViewModels as IEnumerable<DateSnippetWithDepartmentsViewModel>, 
      Request.GetNextPageLink(), 
      Request.GetInlineCount()); 

    return result; 
} 
+0

這對我不起作用與Microsoft.OData.Core.7.0.0一次使用$ expand參數。根據[MSDN](https://msdn.microsoft.com/en-us/library/system.linq.iqueryable(v = vs.110).aspx)_IQueryable接口旨在供查詢提供程序實現。它只應該由實現IQueryable的提供者實現。 ._顯然這不是這種情況,因爲對IQueryable 的'查詢'投下失敗。 –