15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Using WCf Data services with the aDo.neT entity framework ❘ 899<br />

To create a DataServiceCollection < T > instance the class DataServiceCollection defi nes the static<br />

methods Create() <strong>and</strong> CreateTracked() . Create() creates a list that is independent of the data service<br />

context. CreateTracked() keeps track of the objects returned from the data service context so that you can<br />

take advantage of saving the objects by sending the changes to the service.<br />

The Menus property invokes the DataServiceCollection.CreateTracked < T > () method to fi ll a<br />

DataServiceCollection < R.Menu > list named t r a c k e d M e n u s <strong>and</strong> returns this list. The retrieved entities<br />

that are defi ned by the LINQ query are associated with the data service context d at a .<br />

public IEnumerable < R.Menu > Menus<br />

{<br />

get<br />

{<br />

if (trackedMenus == null)<br />

trackedMenus = DataServiceCollection.CreateTracked < R.Menu > (<br />

data,<br />

from m in data.Menus<br />

where m.CategoryId == (comboCategories.SelectedItem as R.Category).Id<br />

& & m.Active<br />

select m);<br />

return trackedMenus;<br />

}<br />

}<br />

code snippet ClientApp/MainWindow.xaml.cs<br />

The DataGrid from the XAML code maps to the Menus property with the Binding markup extension:<br />

< DataGrid Grid.Row="2" ItemsSource="{Binding Path=Menus}" AutoGenerateColumns="False" ><br />

< DataGrid.Columns ><br />

< DataGridTextColumn Binding="{Binding Path=Name}" / ><br />

< DataGridTextColumn Binding="{Binding Path=Description}" / ><br />

< DataGridTextColumn Binding="{Binding Path=Price}" / ><br />

< DataGridTextColumn Binding="{Binding Path=CategoryId}" / ><br />

< /DataGrid.Columns ><br />

< /DataGrid ><br />

code snippet ClientApp/MainWindow.xaml<br />

Using the SelectionChanged event from the ComboBox to select a new category, the menus are retrieved<br />

again with the newly selected category in the h<strong>and</strong>ler method OnCategorySelection() :<br />

private void OnCategorySelection(object sender, SelectionChangedEventArgs e)<br />

{<br />

}<br />

var selectedCategory = comboCategories.SelectedItem as R.Category;<br />

if (selectedCategory != null & & trackedMenus != null)<br />

{<br />

trackedMenus.Clear();<br />

trackedMenus.Load(from m in data.Menus<br />

where m.CategoryId == selectedCategory.Id<br />

select m);<br />

}<br />

code snippet ClientApp/MainWindow.xaml.cs<br />

For more information about observable collections <strong>and</strong> the class ObservableCollection<br />

please consult Chapter 10, “Collections.”<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!