【问题标题】:Implementing $select with WebApi and ODataQueryOptions使用 WebApi 和 ODataQueryOptions 实现 $select
【发布时间】:2013-09-05 08:38:01
【问题描述】:

我正在尝试使用 ODataQueryOptions 通过自定义 DAL 实现一些 OData 功能。

我的 DAL 使用设计时生成的类型化数据表。通过拦截 ODataQueryOptions 的 SelectExpand 属性,我可以让我们的 DAL 仅加载所需的列。

然后我如何只返回所需的数据。

我目前正在将类型数据表中的数据放入 ListOf 一些类型化数据传输对象中,但最终会从不需要的列中得到大量空数据。

我觉得我应该能够执行一些 LINQ 查询来直接从类型化数据表中选择我需要的列,而完全绕过使用类型化 DTO。这可能吗?

【问题讨论】:

    标签: odata asp.net-web-api


    【解决方案1】:

    您需要做与SelectExpandQueryOption.ApplyTo 相同的事情。

    1) 优化查询到后端。与其从数据库中获取整个实体,不如仅获取客户端要求的属性并将其包装成一个 IEdmEntityObject。将集合作为 EdmEntityObjectCollection 返回。此步骤是可选的。您可以选择忽略此步骤并返回 IQueryable 并仍然让 $select 工作。

    2) 告诉 OData 格式化程序仅序列化请求的字段。这可以通过使用扩展方法 Request.SetSelectExpandClause 在 Request 对象上填充 SelectExpandClause 来完成。

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

    【讨论】:

    • 谢谢。我对后端的东西很好,我从数据库中加载了一个类型化的数据表,其中只有 $select 子句中的列,然后我将其放入 ListOf 类型化 DTO。您能否稍微扩展一下第二部分。我的控制器继承自 APIController,我有一个 Get 方法将 ListOf(TypedDTO) 作为 IEnumerable(Of TypedDTO) 返回。没有 EF,我也没有 IQueryable - 我都是手工完成的。正如你所说,我只需要弄清楚如何只序列化请求的字段。
    • 嗨。有没有机会请您提供更多详细信息。我刚刚意识到我实际上是在尝试关注您的一篇博文 blogs.msdn.com/b/webdev/archive/2013/02/25/… 我不知道如何访问 ODataFormatter 来告诉它只序列化请求的字段。
    • 谢谢。我似乎无权访问 SetSelectExpandClause - 不是 System.Net.Http.HttpRequestMessage 的成员。我使用的是旧版本的东西吗?
    • 我刚刚去了 Request.Properties("MS_SelectExpandClause") = queryOptions.SelectExpand.SelectExpandClause ,这似乎工作
    • Request.ODataProperties().SelectExpandClause = queryOptions.SelectExpand.SelectExpandClause;
    猜你喜欢
    • 2019-09-02
    • 1970-01-01
    • 2013-09-23
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 2015-11-04
    相关资源
    最近更新 更多