繁体   English   中英

使用WebApi和ODataQueryOptions实现$ select

[英]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.

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