ADO.NET Data Services : How to consume my ADO.NET Data Services in WPF


Introduction

In this post I will talk about how you can consume your ADO.NET Data Services. My examples will be based on WPF.

For more information on Data Services, I suggest you to read my previous posts:

Consuming in WPF

Creates a WPF application named MyWPFApplication.

image

Add a reference to your Data Service, right click on MyWPFApplication project, and select Add service reference. A windows appears, define the address, rename the namespace with MyDataServiceProxy and click on OK button.

image

In MainWindow.xaml.cs, write the following code:

Code Snippet
  1. public partial class MainWindow : Window
  2. {
  3.     public MainWindow()
  4.     {
  5.         InitializeComponent();
  6.         this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
  7.     }
  8.  
  9.     void MainWindow_Loaded(object sender, RoutedEventArgs e)
  10.     {
  11.  
  12.         // Define the URI of the Data Service Query
  13.         Uri uri = new Uri(@"http://localhost:34570/AdventureWorksService.svc/");
  14.         // Create an instance of the Data Service context
  15.         MyDataServiceProxy.AdventureWorksModel.AdventureWorksEntities adventureWorksProxy = new MyDataServiceProxy.AdventureWorksModel.AdventureWorksEntities(uri);
  16.         // Create your query
  17.         var query = (from product in adventureWorksProxy.Products
  18.                     select product).Take(10);
  19.         // Set the qury result into the DataContext
  20.         this.DataContext = query;
  21.     }
  22. }

In the loaded event, instantiate your DataService. Create a simple request using Linq syntax and put this query into the DataContext.

In MainWindow.xaml, bind the data grid with the DataContext :

Code Snippet
  1. <Window x:Class="MyWpfApplication.MainWindow"
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.         Title="MainWindow" Height="350" Width="525">
  5.     <Grid>
  6.         <DataGrid AutoGenerateColumns="true" Height="287" HorizontalAlignment="Left" Margin="12,12,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="479"
  7.                   ItemsSource="{Binding}">
  8.         </DataGrid>
  9.     </Grid>
  10. </Window>

Press F5 and here is the result:

image

This post shows how easy it is to consume Data Services with WPF. Just few code lines are needed 😉

Skip to main content