2013-04-23 35 views
0

我想在我的所有藏品上使用iqueryable,以便獲得所有的odata功能。不過,我需要將請求的響應格式化爲以下字段:如何格式化iqueryable mvc 4 web api請求?

{ 
    href: "url to resouce", 
    length: 10, 
    items: [ 
    "(IQueryable results)" 
    ] 
} 

格式化響應不是最難的部分,但保持odata「stuff」的所有工作是。

所以我的代碼看起來像;

MyFormattedResponse.Href = "poop.com"; 
MyFormattedResponse.Length = 0; 
MyFormattedResponse.Items = _myRepo.Gets(); 
Request.CreateResponse(HttpStatusCode.OK, MyFormattedResponse); 

但我得到的錯誤是:

的行動控制器「MyResource」返回類型爲 '獲取「爲MyObject」不能支持查詢。確保返回的 內容的類型是IEnumerable,IQueryable或通用形式的 接口。

這是我可以在媒體格式化器或過濾器中構建的東西嗎?

我真的想保持的OData迷死...

回答

0

看看這個答案我提供:

Web API Queryable - how to apply AutoMapper?

你的情況是類似的,你可以做這樣的事情:

public MyFormattedResponse Get(ODataQueryOptions<Person> query) 
{ 
    var results = query.ApplyTo(_myRepo.Gets()) as IEnumerable<Person>; 
    return new MyFormattedResponse() { Href = "foo.com", Length = 5, Items = results }; 
} 

確保您刪除了[Queryable]屬性。

+0

非常感謝你! – Noob 2013-05-07 12:59:20