处理选择核心中的odataqueryoptions?

时间:2017-11-03 21:18:16

标签: c# .net asp.net-core visual-studio-2017 odata

我有一个常规控制器,具有odata功能:

[Route("[controller]")]
public class ChannelsController : Controller
{
    private readonly ChannelContext db = new ChannelContext();
    public IQueryable<PrdChannel> Get()
    {
        var entities = db.PrdChannel.AsQueryable();
        var modelManager = (IODataModelManger) HttpContext.RequestServices.GetService(typeof(IODataModelManger));
        var model = modelManager.GetModel(nameof(ProductConfiguration));
        var queryContext = new ODataQueryContext(model, typeof(PrdChannel), null);
        var queryOptions = new ODataQueryOptions(queryContext, HttpContext.Request);

        return queryOptions
            .ApplyTo(entities, new ODataQuerySettings
            {
                HandleNullPropagation = HandleNullPropagationOption.True
            })
            .Cast<PrdChannel>();
    }
}

我可以发出GET:https://myservice/Channel?$filter=cable lt 10

但是,当我尝试$select时,它不起作用!

https://myservice/Channel?$select=cable

根据OdataQueryOptions的定义,它不支持select / expand。

问题:我们如何在aspnetcore中支持$select

也许这应该是一个ODataController?

1 个答案:

答案 0 :(得分:0)

重复项:Can't apply $select when using ODataQueryOptions

要在OData中支持$ select,您不能将IQueryable强制转换为定义的类型,而需要使用dynamic类型。

    public IQueryable<dynamic> Get()
    {
        ... your code ...
        return queryOptions
            .ApplyTo(entities, new ODataQuerySettings
            {
                HandleNullPropagation = HandleNullPropagationOption.True
            })
            as IQueryable<dynamic>;
    }