Querying the Data Service (ADO.NET Data Services/Silverlight)
This page is specific to:Microsoft Version:Silverlight 3
Silverlight
Querying the Data Service (ADO.NET Data Services/Silverlight)

In this task, you will query the data service and bind the returned entity data to controls in the application, which you defined in the previous task. You create and execute the query asynchronously by using the NorthwindEntities class, which derives from the DataServiceContext class. You generated this context class from the data service metadata by using the add service reference tool in the previous task. For more information, see Working with .NET Framework Client Libraries (ADO.NET Data Services).

NoteNote:

Because you asynchronously access the data service by using network protocols, you must use the BeginInvoke method of the Dispatcher class to correctly marshal the response operation back to the main application thread (the UI thread) of your Silverlight-based application. For more information, see Synchronizing Data for Multithreading.

To query for orders that belong to a specified customer

  1. Open the MainPage.xaml.cs source code file of the Silverlight project.

  2. Add the following using directives (Imports in Visual Basic):

    Imports System.Windows
    Imports System.Data.Services.Client
    Imports System.Collections.ObjectModel
    Imports System.Collections.Specialized
    Imports SilverlightClient.Northwind
    
    
    
  3. Add the following type definitions to the MainPage class:

    Dim svcContext
    Dim ordersBindingCollection
    Dim detailsBindingCollection
    
    
    
  4. In the public constructor method for the MainPage class, insert the following code that initializes the data binding collections.

    ' Create the binding collections.
    ordersBindingCollection = New ObservableCollection(Of Orders)()
    detailsBindingCollection = New ObservableCollection(Of Order_Details)()
    
    
    
  5. Add the following methods to the MainPage class. These methods are called when the getCustomerOrders button is clicked. The first method reinitializes the DataServiceContext and clears the binding collections. The second method obtains an instance of DataServiceQuery<(Of <(TElement>)>) of the Customers type from the context. The AddQueryOption method is called two times on this query; one time to add a $filter query option to return only a specific customer and again to add an $expand query option to return orders related to the returned customer. The returned Orders objects are loaded into an ObservableCollection<(Of <(T>)>) that is bound to the DataGrid.

    Private Sub ResetBindingData()
        ' Create a new data service context.
        svcContext = _
            New NorthwindEntities(New Uri("Northwind.svc", UriKind.Relative))
    
        ordersBindingCollection.Clear()
        detailsBindingCollection.Clear()
    End Sub
    ' We need to persist the result of an operation 
    ' to be able to invoke the dispatcher.
    Private currentResult As IAsyncResult
    Private Sub getCustomerOrders_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        ' Instantiate the data service context and clear any existing bindings.
        ResetBindingData()
    
        ' Define the delegate to callback into the process
        Dim callback As AsyncCallback = AddressOf OnCustomerOrdersQueryComplete
    
        ' Define the filter condition based on the customer ID.
        Dim filterExpression = "CustomerID eq '" & Me.customerId.Text & "'"
    
        ' Define a query to return the specifed customer and related orders.
        Dim query As DataServiceQuery(Of Customers) = _
        svcContext.Customers() _
                .AddQueryOption("$filter", filterExpression).Expand("Orders")
        Try
            ' Begin the query execution.
            query.BeginExecute(callback, query)
        Catch ex As Exception
            messageTextBlock.Text = ex.Message
        End Try
    End Sub
    Private Sub OnCustomerOrdersQueryComplete(ByVal result As IAsyncResult)
        ' Persist the query result for the delegate.
        currentResult = result
    
        ' Use the Dispatcher to ensure that the 
        ' asynchronous call returns in the correct thread.
        Dispatcher.BeginInvoke(AddressOf QueryCompletedByDispatcher)
    End Sub
    Private Sub QueryCompletedByDispatcher()
        Try
            ' Get the original query back from the result.
            Dim query = CType(currentResult.AsyncState, DataServiceQuery(Of Customers))
    
            Dim returnedCustomer = query.EndExecute(currentResult).FirstOrDefault()
    
            If returnedCustomer IsNot Nothing Then
    
                ' Load the retuned orders into the binding collection.
                For Each order As Orders In returnedCustomer.Orders
                    ordersBindingCollection.Add(order)
                Next
    
                ' Bind the grid control to the collection and update the layout.
                Me.ordersGrid.DataContext = ordersBindingCollection
                Me.ordersGrid.UpdateLayout()
    
                ' Hide the relationship property columns.
                Me.ordersGrid.Columns(8).Visibility = Visibility.Collapsed
                Me.ordersGrid.Columns(11).Visibility = Visibility.Collapsed
                Me.ordersGrid.Columns(12).Visibility = Visibility.Collapsed
            End If
        Catch ex As DataServiceQueryException
            Me.messageTextBlock.Text = String.Format("Error: {0} - {1}", _
                ex.Response.StatusCode.ToString(), ex.Response.Error.Message)
        End Try
    End Sub
    
    
    

To build and run the application

  1. From the Debug menu, select Start Debugging or Start Without Debugging.

    This builds and starts the application.

  2. When the page loads, enter a value in the Customer ID text box (a valid value of ALFKI is provided), and then click Get Orders.

    This displays the orders that belong to that customer.

Next Steps

You have successfully created a query that returns a specific Customers object and related Orders objects from the Northwind data service, and you have bound those Orders objects to a grid control. Next, you will load specific Order_Details objects from the data service and bind them to a second data grid:

Loading Related Entities

Community Content

Problem
Added by:StAshlar
Hi, I've go this set up but when I click the 'Get Orders' button I always get:

Error:402 - Na error occured while saving changes.

Am I missing something here?

Cheers
Ashlar
© 2009 Microsoft Corporation. All rights reserved.   Terms of Use | Trademarks | Privacy Statement
Page view tracker
Rate the Lightweight library
x
Lightweight builds on ScriptFree (loband) by adding features you've requested: a SearchBox and default code language selection.
Do you like the SearchBox?
Do you like the tabbed code blocks?
How useful is this topic?
Tell us more.
Thanks
x
You're helping to improve MSDN Online.
Feedback
Switch View
Classic
Lightweight Beta
ScriptFree
Switch View