5

这是我的问题。我正在使用 ASP.NET Web API 2.0 和 QueryableAttribute 来利用一些 OData 过滤功能。

public class VideoController : ApiController
{
    [HttpGet]
    [Route("activevideos")]
    [Queryable]
    public IEnumerable<Video> GetActiveVideos(ODataQueryOptions<Video> options)
    {
        return new GetvContext().Videos.Where(c => c.IsActive);
    }        
}

现在,我有一个类,我一直在使用它来修改响应对象和包含的实体。这在我开始使用 QueryableAttribute 之前工作正常。在此之前,我从前一个方法而不是 IEnumerable 返回一个列表。

public class TestMessageProcessHandler : MessageProcessingHandler
{
    protected override HttpResponseMessage ProcessResponse(
        HttpResponseMessage response, CancellationToken cancellationToken)
    {

        var content = ((ObjectContent)(response.Content)).Value;
        // Do something here with the content.  This used to be a List<Video> 
        // but now the object it is of type: 
        // System.Data.Entity.Infrastructure.DbQuery<System.Web.Http.OData.Query.Expressions.SelectExpandBinder.SelectSome<Content.Api.Video>>
    }
}

我需要能够从中获取实体,但我不确定如何从类型中获取:

System.Data.Entity.Infrastructure.DbQuery<System.Web.Http.OData.Query.Expressions.SelectExpandBinder.SelectSome<Content.Api.Video>>List<Video>这样我可以修改Video对象。

4

3 回答 3

1

删除[Queryable]属性并自己管理数据查询 - 如下所示:

public class VideoController : ApiController
{
    [HttpGet]
    [Route("activevideos")]
    public IList<Video> GetActiveVideos(ODataQueryOptions<Video> options)
    {
        var s = new ODataQuerySettings() { PageSize = 1 };
        var result = options.ApplyTo(
            new GetvContext().Videos.Where(c => c.IsActive), s)
            .ToList();

        return result;
    }        
}
于 2013-10-24T15:00:30.533 回答
0

你不能只做一个 ToList() - DbQuery 实现 IQueryable ...

例如

var content = ((ObjectContent)(response.Content)).Value;
var queryable = content as IQueryable<Video>;
var list = queryable.ToList();
于 2014-03-09T04:36:55.547 回答
0

Most probably you are getting this problem because you specified which fields should be selected by your OData query (for example, $select=Nr,Date). If you won't do this, after applying query options OData won't return a SelectSome objects, it will return the same objects you are querying, in your case Video. So you can easily modify these objects server-side before returning them to client.

And if you need to exclude properties from Video object which you don't need, instead of $select query option you can use a DTO instead of your Video object and include in this DTO only those fields you need.

Yes, this is a workaround, and hopefully there will be better means to do deal with server-side logic in the future versions of this library

于 2015-11-24T13:33:16.450 回答