Sometimes we may not want to show all the fields in an entity. For example, the client makes the following request:
Locaohost:43321/api/groups/1/items?fields=id
Locaohost:43321/api/groups/1/items?fields=id,name
Above, for item this class, we may just want to display the ID, also may want to display the ID and the name, and so on.
How to achieve it?
→ back end accepts fields The value of this query string, split into an array or collection
→ Iterate through these fields, get the values of the fields using reflection, and store each key value.
Assume the following field:
Public classgroup{ Public intid{Get;Set;} Public intuserid{Get;Set;} Public stringtitle{Get;Set;} Public stringdescritpion{Get;Set;} Public intstatusid{Get;Set;} PublicIcollection<item> items{Get;Set;}} Public classitem{ Public intid{Get;Set;} Public stringname{Get;Set;}}
The controller for item is as follows:
Public classitemscontroller:apicontroller{[Route ("Groups/{groupid}/items", name="Itemsforgroup")] PublicIhttpactionresult Get (intGroupId,stringFields =NULL) {List<string> lstoffields =Newlist<string>(); if(Fields! =NULL) {Lstoffields= fields. ToLower (). Split ("'). ToList (); } varresult =_repo. GetItems (). ToList (). Select (e=Itemfactory.createdatashapedobject (E, lstoffields)); returnOk (Result); }} PublicStaicclassitemfactory{ Public ObjectCreatedatashapedobject (item item, list<string>lstoffields) { if(!Lstoffields.any ()) { returnitem; } Else { //run-time objectsExpandobject Objecttoreturn =NewExpandobject (); foreach(varFieldinchlstoffields) { //Get field values varFieldvalue =item. GetType (). GetProperty (field, Bindingflags.ignorecase| BindingFlags.Public |bindingflags.instance). GetValue (item,NULL); ((IDictionary<string,Object>) (Objecttoreturn). ADD (field, fieldvalue); } returnObjecttoreturn; } }}
Above, Expandobject is the runtime object, implements the Idictionary<string, object> interface, through reflection, the field as the Expandobject key, the field value as the Expandobject value.
Partial fields in an entity are displayed by URI in the ASP.