2

I am using OData services for my Web Api to provide pagination to my client app. This is the code for one of my controller methods.

// Get all Categories
    [HttpGet]
    [ActionName("all")]
    public ODataResult<DataAccess.Model.Category> GetCategoryList(ODataQueryOptions options)
    {          

        var categoryList = this.Repository.GetCategories().AsQueryable<Category>();

        var results = (options.ApplyTo(categoryList) as IQueryable<DataAccess.Model.Category>);                     


        long count = categoryList.Count();

        if (count == 0) 
            count = 1; // throws up an ArgumentException error if the count is less than 1

        return new ODataResult<DataAccess.Model.Category>(results, null, count);

    }

But when i use any OData protocols in the api call like api/Category/all?$skip&$top=5 it doesnt return me the exact order in which the 5-10 elements are there in the db (i.e sorted by their primary key=ID). I can fix this by using $orderby=ID for all my API calls, but i want to know if i can avoid it. Am i doing anything wrong here because by default the OData services should return in the same order as they are in the db right? Please let me know if you have any ideas or suggestions.

Thanks

4

2 回答 2

4

默认情况下,我们通过 key 属性对结果集进行排序,以确保排序稳定(如果不是分页会被破坏)。所以,看看你的模型是什么会很有趣,即 DataAccess.Model.Category 的样子。此外,如果您想自己进行稳定排序并禁用 webapi 推断顺序,则可以将 ODataQuerySettings.EnsureStableOrdering (false) 用于 ApplyTo 的另一个重载,即

public virtual IQueryable ApplyTo(IQueryable query, ODataQuerySettings querySettings);
于 2012-11-28T01:44:47.290 回答
2

除非客户要求,否则 OData 中的任何内容都不会强制执行特定的排序。$top 和 $skip 查询选项强制“一些稳定的”排序,默认情况下(在 .NET 实现中)使用键属性(主键)的排序,但如果您只是询问集合中的所有实体,服务将不强制任何排序(因为它不需要),因此将返回底层提供者给出的任何顺序(取决于数据库等)。

于 2012-11-27T13:58:49.570 回答