【问题标题】:WebApi 2.0 OData, obtain list of SQL tables used in the queryWebApi 2.0 OData,获取查询中使用的SQL表列表
【发布时间】:2016-08-04 09:16:24
【问题描述】:

我有一个相当标准的 WebApi 2.0 OData 4.0 网络服务,使用 EF5 和代码优先方法。该服务有效,我可以通过外键查询实体和相关实体。

该服务是只读的,控制器只实现了 Get 和 Get-by-key。

public class MyTableController : MyDbController
{
    [EnableQuery]
    public IQueryable<MyTable> Get()
    {
        return db.MyTable;
    }

    [EnableQuery]
    public SingleResult<MyTable> Get([FromODataUri] int key)
    {
        IQueryable<MyTable> result = db.MyTable.Where(p => p.pk == key);
        return SingleResult.Create(result);
    }
}

在两个 Get() 实现中,我都希望能够访问 OData 中使用的表列表和生成的 SQL 查询。 MyTable 显然是其中之一,但我如何获得其他的(其中包括(嵌套)$expand 中使用的那些)?我可以尝试自己解析 URL,但这似乎不是一个很好的方法。

【问题讨论】:

    标签: c# asp.net-web-api odata


    【解决方案1】:
    1. 创建一个继承自 EnableQueryAttribute 的类 CustomizeAttribute
    2. 覆盖此方法:public virtual IQueryable ApplyQuery
    3. 然后你在这个方法中得到queryOptions,你可以去SelectExpandQueryOption找到ExpandItem,然后你就得到了所有的表。

      public override IQueryable ApplyQuery(IQueryable queryable, ODataQueryOptions queryOptions)
      {
          if (queryOptions.SelectExpand != null)
          {
              foreach (var selectItem in queryOptions.SelectExpand.SelectExpandClause.SelectedItems)
              {
                  var expandedItem = selectItem as ExpandedNavigationSelectItem;
                  if (expandedItem != null)
                  {
                      // get the entitySetName, tableName
                      string entitySetName = expandedItem.NavigationSource.Name;
                     // can go recursive with expandItem.SelectExpandClause in case we have $epxand=A($expand=B)
                  }
              }
          }
          return base.ApplyQuery(queryable, queryOptions);
      }
      
    4. 在控制器方法上使用这个属性

      [CustomizeAttribute]
      public IQueryable<MyTable> Get()
      {
          return db.MyTable;
      }
      

    【讨论】:

      猜你喜欢
      • 2011-12-06
      • 2018-07-24
      • 2015-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多