To query an OData producer, such as the eBay OData service, first create an instance of the generated OData model class, using the service root URI, like so:
EBayData ebayData = new EBayData(new Uri("http://ebayodata.cloudapp.net/"));
We then create a DataServiceCollection
, which is used to query the OData service asynchronously and to populate itself with the objects representing items in the response feed. The DataServiceCollection
type inherits from ObservableCollection
, which means it supports INotifyCollectionChanged
out of the box, and it can be used directly within the user interface.
To instantiate a DataServiceCollection
, an OData model instance is passed to its constructor, like so:
searchResult = new DataServiceCollection<Item>(ebayData);
Because the DataServiceCollection
queries the OData producer asynchronously, we subscribe to its LoadCompleted
handler to be notified when the query has completed, as shown in the following example:
searchResult.LoadCompleted
+= (sender, args) =>
{
if (args.Error != null)
{
/* Handle search error. */
}
};
Subscribing to the LoadCompleted
event is, however, optional. Regardless of whether it is handled, if an error does not occur, the collection is populated automatically after the call completes.
A second URI is used to specify the resources and query options:
var itemsUri = new Uri("/Items?search=phone&$top=5&$select=Title",
UriKind.Relative);
This second URI is then used to fetch the results, using the LoadAsync
method of the DataServiceCollection
:
searchResult.LoadAsync(itemsUri);
Alternatively, a DataServiceQuery
can be created, which eliminates the manual creation of the request URI, as shown:
IQueryable<Item> serviceQuery
= ebayData.Items.AddQueryOption("search", "phone")
.AddQueryOption("$top", 5);
With an IQueryable<T>
the search results can be further restricted using LINQ to OData, as demonstrated in the following example:
serviceQuery = from item in serviceQuery
where item.CurrentPrice > 100.0
select item;
searchResult.LoadAsync(serviceQuery);
When the query completes, the searchResult DataServiceCollection
is automatically populated with strongly typed objects representing the resource; in this case it produces eBay Item
objects.
Although OData is a standard, OData services differ in their coverage of query options; all query options are not provided by all services. Be sure to read any relevant documentation for the OData service that you intend to consume in your app.
The full API documentation for the eBay OData service can be found at http://ebayodata.cloudapp.net/docs.
3.14.135.107