[英]How to enable $expand and $select on ODataQueryOptions?
[英]Implementing $select with WebApi and ODataQueryOptions
我正在嘗試使用ODataQueryOptions通過自定義DAL實現一些OData功能。
我的DAL使用設計時生成的類型化數據表。 通過攔截ODataQueryOptions的SelectExpand屬性,我可以使我們的DAL僅加載所需的列。
然后我該如何只返回所需的數據。
目前,我正在將類型數據表中的數據放到一些類型化數據傳輸對象的ListOf中,但是最后從不需要的列中得到大量空數據。
我覺得我應該能夠進行一些LINQ查詢,從而直接從類型化數據表中直接選擇我需要的列,而無需使用類型化DTO。 這可能嗎?
您需要執行與SelectExpandQueryOption.ApplyTo相同的操作。
1)優化查詢到后端。 而不是從數據庫中獲取整個實體,僅獲取客戶端要求的屬性並將其包裝在IEdmEntityObject中。 將集合作為EdmEntityObjectCollection返回。 此步驟是可選的。 您可以選擇忽略此步驟並返回IQueryable並仍然使$ select起作用。
2)告訴OData格式化程序僅序列化請求的字段。 這可以通過使用擴展方法Request.SetSelectExpandClause
將SelectExpandClause填充到Request對象Request.SetSelectExpandClause
。
public class CustomersController : ODataController
{
public IEnumerable<Customer> Get(ODataQueryOptions<Customer> query)
{
Customer[] customers = new[] { new Customer { ID = 42, Name = "Raghu" } };
// Apply query
var result = customers;
// set the SelectExpandClause on the request to hint the odata formatter to
// select/expand only the fields mentioned in the SelectExpandClause.
if (query.SelectExpand != null)
{
Request.SetSelectExpandClause(query.SelectExpand.SelectExpandClause);
}
return result;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.