简体   繁体   中英

Implementing $select with WebApi and ODataQueryOptions

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM