MVC API OData Query Options $inlinecount, $format options

Source: Internet
Author: User

Online Baidu "OData syntax" will come out a lot of results, one of which is more consistent, that is, OData support a few syntax:

$filter conditional expression--the Where Condition query for the SQL statement, such as:/categories? $filter =name eq ' Liumang '

$expand contains attributes and relationships-foreign key relationships for the corresponding table, such as:/categories? $expand =products

$select a list of query fields-corresponding to the fields following the SQL statement select, such as:/categories? $select =id,name

$count number of queries--the total number of records returned based on the current query criteria, such as 10 records in the Categories table,/categories?count or/categories?count=true

(PS: This article I did not find the exact usage, in the Allowedqueryoptions enumeration also does not list this option)

$orderby sort-corresponds to the SQL statement order BY statement, such as:/categories? $orderby =id,name,/categories? $orderby =id,name Desc (ASC),/categories? $orderby =id desc,name ASC

$skip the current query skips how many data, and then return the query results, such as:/categories? $orderby =id& $skip = 10, if the ID is sequential, then return all data from the id=11

$top returns the first number of data for the current query, such as/categories? $top =10

Skip and top are generally used together to make paged queries, such as/categories? $skip =10& $top =10,/categories? $skip =20& $top = 10, so you can make a pagesize For 10 of the paging query

$inlinecount Returns the number of records for the current query condition, such as:/categories? $inlinecount =allpages, if Categories has 23 data,

Something that $skiptoken such as a cursor or a bookmark

$metadata Display Metadata

The above is found on the Internet, data is very complete, many of the cases are given, but in my actual use, but only a few data can be used, the other is not applicable, I analyze the reasons may be as follows:

1: I do the project is integrated in the MVC and the API inside, and many examples of the online is mostly WCF case column, I am not quite clear is not this reason, because WCF I only know fur, no depth

2: In assembly System.Web.Http.OData.dll, there is a comment in v4.0.0.0:

//        // Summary:         //      Gets or sets the query parameters that are allowed to be used internally within the query. The default values are all query options, including $filter, $skip, $top, $orderby, $expand, $select        , $inlineCount, $format// ,      and $skipToken.         //        // return Result:         //      returns System.Web.Http.OData.Query.AllowedQueryOptions.
Public allowedqueryoptions allowedqueryoptions {get; set;}

You can see that the Allowedqueryoptions enumeration is listed above or there are some discrepancies

3: Also in assembly System.Web.Http.OData.dll, there is a comment in v4.0.0.0:

namespace/ / Abstract:    //      This key defines a composite OData query option that can be used to perform query composition. This item currently supports only $filter, $orderby, $top, and $skip.     //    // type parameter:     //    TEntity:    [odataqueryparameterbinding]    publicclass Odataqueryoptions<tentity>: Odataqueryoptions

You can see that only four options are supported, which is consistent with my usage in the project.

PS: One thing that makes me wonder is that OData 4.0 supports all of the query options listed above, and when API 2.2 is released, it's a clear support for OData 4.0, and I don't know what causes me to support only four options in my project now.

After saying so much, back to the topic above, in fact $filter, $orderby, $top and $skip four options are available to support about 90% of the query function

The remaining 10% features such as the total number of records that must be known when paging queries, return JSON strings, foreign key relationships, and more

Here's what I found on the internet about $inlinecount, $format solution

$format

Requires OData support the $format parameter requires only one sentence to

 Public Static classWebapiconfig { Public Static voidRegister (httpconfiguration config) {config. Routes.maphttproute (Name:"Defaultapi", Routetemplate:"Api/{controller}/{id}", defaults:New{id =routeparameter.optional});
Add the following code to support $format query options, of course, you need to add the assembly System.Net.Http.Formatting.dll config. Formatters.JsonFormatter.AddQueryStringMapping ("$format","JSON","Application/json"); } }

$inlinecount

This also does not require too many complex operations, the code is as follows

 Public classTestcontroller:apicontroller {TESTBLL DB=NewTESTBLL ();  PublicPageresult<dict> Get (odataqueryoptions<dict>options) {            intPageSize = 10;odataquerysettings Settings=Newodataquerysettings () {PageSize=PageSize}; IQueryable Results=options. ApplyTo (DB. FindAll ().            AsQueryable (), settings); return NewPageresult<dict>(Results asIenumerable<dict>, Request.getnextpagelink (), Request.getinlinecount ()); }    }

Query url:http://localhost:3812/api/test? $skip =20& $inlinecount =allpages

The return format is as follows:

{"Items": ["JSON string"],"Nextpagelink": "Next page URL", "Count": number//total number of records} Reference network information: http://www.2cto.com/kf/201312/266851.html Here I did an experiment, Because in the actual case of the environment, the user can choose to display the number of records per page, but this column is written dead. So I modified the code as follows:
int pageSize = options. Top = = null? 10:options. Top.value;

When the user chooses the number of records, according to the user's choice of settings, you can dynamically return the next page of records, but the returned nextpagelink value is null, when I remove the top parameter, the return is normal data

Here is the System.Web.Http.OData.dll after the source code, I think it may be sent in the request, when the parameters are set to determine the top parameters caused by the

 Public StaticUri Getnextpagelink ( Thishttprequestmessage request) {    ObjectObj2; if(Request = =NULL)    {        ThrowError.argumentnull ("Request"); }    if(Request.get_properties (). TryGetValue ("Ms_nextpagelink", outobj2)) {        return(Obj2 asUri); }    return NULL;} 

Above is the $format and $inlinecount parameters of the Setup method, $expand parameters I found the relevant information and then collated.

MVC API OData Query Options $inlinecount, $format options

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.