简体   繁体   English

如何将 SelectExpandQueryOption 转换为 IQueryable<T> 在 WebAPI 中使用 OData 时?

[英]How to cast SelectExpandQueryOption to IQueryable<T> when using OData in WebAPI?

I have a WebAPI that is written in C# on the top of ASP.NET Core/5 framework.我在 ASP.NET Core/5 框架的顶部有一个用 C# 编写的 WebAPI。

I enabled odata for my API.我为我的 API 启用了odata I am trying to manually apply the odata filter, order by clause, select columns and the expands.我正在尝试手动应用 odata 过滤器、order by 子句、选择列和扩展。

Here is how I am trying to manually build the query using the ODataQueryOptions这是我尝试使用ODataQueryOptions手动构建查询的ODataQueryOptions

protected IQueryable<TModel> BuildQuery(ODataQueryOptions<TModel> queryOptions, ODataQuerySettings settings)
{
    IQueryable<TModel> query = DbSet;

    if (queryOptions.SelectExpand != null)
    {
        var queryable = queryOptions.SelectExpand.ApplyTo(query, settings);

        query = queryable.Cast<TModel>(); // this causes an error
    }

    if (queryOptions.Filter != null)
    {
        query = queryOptions.Filter.ApplyTo(query, settings) as IQueryable<TModel>;  // this works!
    }

    if (queryOptions.OrderBy != null)
    {
        query = queryOptions.OrderBy.ApplyTo(query); // this works!
    }

    return query;
}

Everything above works great up until I try to expand a navigation property.在我尝试扩展导航属性之前,上面的所有内容都很好用。 When I do I get the following error当我这样做时,我收到以下错误

System.InvalidOperationException: 'No coercion operator is defined between types 'Microsoft.AspNetCore.OData.Query.Wrapper.SelectAllAndExpand`1[MyModel]' and 'MyModel'.'

Is there some sort of mapping that I need to do when defining the IEdmModel to build the navigation relations?在定义IEdmModel以构建导航关系时,是否需要进行某种映射?

How can I correctly convert/cast IQueryable<Microsoft.AspNetCore.OData.Query.Wrapper.SelectAllAndExpand<TEntity>> to IQueryable<TEntity> ?如何正确转换/转换IQueryable<Microsoft.AspNetCore.OData.Query.Wrapper.SelectAllAndExpand<TEntity>>IQueryable<TEntity>

Here is the code behind SelectAllAndExpand这是SelectAllAndExpand背后的代码

You can't directly cast不能直接投

var queryable = queryOptions.SelectExpand.ApplyTo(query, settings);

to IQueryable<TModel> , because it different type of object.IQueryable<TModel> ,因为它是不同类型的对象。

If there is no Projection ( Select ) or Expand - you will get a regular object, but after Projection and Expand - it's a completely different thing.如果没有 Projection ( Select ) 或 Expand - 您将获得一个常规对象,但是在 Projection 和 Expand 之后 - 这是完全不同的事情。 Depending on your tasks, you should handle SelectAllAndExpand<TModel> or remove SelectExpand.ApplyTo(..) .根据您的任务,您应该处理SelectAllAndExpand<TModel>或删除SelectExpand.ApplyTo(..)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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