Implementing $select with WebApi and ODataQueryOptions

后端 未结 1 954
滥情空心
滥情空心 2021-01-22 08:52

I\'m trying to implement some OData functionaility with a custom DAL using ODataQueryOptions.

My DAL uses design time generated typed data tables. By intercepting the S

相关标签:
1条回答
  • 2021-01-22 09:36

    You need to do the same thing that SelectExpandQueryOption.ApplyTo does.

    1) Optimize the query to the backend. Instead of getting the whole entity from the database, get only the properties the client asked for and wrap that result in an IEdmEntityObject. Return the collection as EdmEntityObjectCollection. This step is optional. You could choose to ignore this step and return IQueryable and still get $select to work.

    2) Tell the OData formatter to serialize only the requested fields. This can be done by stuffing the SelectExpandClause on the Request object using the extension method 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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题