Implementing $select with WebApi and ODataQueryOptions

匿名 (未验证) 提交于 2019-12-03 01:12:01

问题:

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 SelectExpand property of ODataQueryOptions i can get our DAL to only load the columns required.

How do i then return just the data required.

I am currently tipping the data from our type datatables into a ListOf some typed data tranfer objects but then end up with lots of null data from the columns which aren't required.

I feel like i should be able do some LINQ query to select the just the columns I need straight from the typed datatable bypassing using typed DTOs altogether. Is this possible?

回答1:

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;     } } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!