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:
- How to create an ADO.NET Data Services with Visual Studio 2010 beta2
- How to request your ADO.NET DataServices
- Operations and Interceptors Consuming ADO.NET Data Services in WPF
Consuming in WPF
Creates a WPF application named MyWPFApplication.
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.
In MainWindow.xaml.cs, write the following code:
Code Snippet
- public partial class MainWindow : Window
- {
- public MainWindow()
- {
- InitializeComponent();
- this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
- }
- void MainWindow_Loaded(object sender, RoutedEventArgs e)
- {
- // Define the URI of the Data Service Query
- Uri uri = new Uri(@"https://localhost:34570/AdventureWorksService.svc/");
- // Create an instance of the Data Service context
- MyDataServiceProxy.AdventureWorksModel.AdventureWorksEntities adventureWorksProxy = new MyDataServiceProxy.AdventureWorksModel.AdventureWorksEntities(uri);
- // Create your query
- var query = (from product in adventureWorksProxy.Products
- select product).Take(10);
- // Set the qury result into the DataContext
- this.DataContext = query;
- }
- }
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
- <Window x:Class="MyWpfApplication.MainWindow"
- xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
- Title="MainWindow" Height="350" Width="525">
- <Grid>
- <DataGrid AutoGenerateColumns="true" Height="287" HorizontalAlignment="Left" Margin="12,12,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="479"
- ItemsSource="{Binding}">
- </DataGrid>
- </Grid>
- </Window>
Press F5 and here is the result:
This post shows how easy it is to consume Data Services with WPF. Just few code lines are needed ;-)