Many demos of WCF RIA Services show off using the DomainDataSource Class to in a declarative manner to quickly throw together a data-enabled application. And in VS2010, there is added support for using the Data Sources Window to Drag/Drop data entities onto the designer --- this action also adds a DomainDataSource instance into your XAML.
For many applications, using a DomainDataSource in XAML is fine and enables RAD development. But some pundits (Hi Shawn!) argue that having direct interaction with the Data Layer from the UI Layer is bad for proper Model/View separation, testability, and general karma.
Luckily, there are several ways to use WCF RIA Services programmatically - without relying on the DomainDataSource controls in XAML. Let's take a look at some of these programmatic methods:
Download the Demo Code
* requires SL4/VS2010 Beta 2, WCF RIA Services Beta
Using the DomainContext
The DomainContext class allows the Silverlight client to access the Domain Service Class you created on the server side. A new DomainContext class is automatically generated on the client side for you when you create a new Domain Service.
In the demo, our DomainContext class is named BeerContext. We can load all of the Beer rows from the database using the Load method, passing in an entity query that exists in our Domain Service:
BeerContext _beerContext = new BeerContext();
LoadOperation
<Beer> loadBeers = _beerContext.Load(_beerContext.GetBeersQuery());
grdLoadFromContext.ItemsSource = loadBeers.Entities;
We can also use a LINQ query against a DomainContext, allowing us to request more specific records:
EntityQuery<Beer> beerQuery = from b in _beerContext.GetBeersQuery()
where b.BrewerId == 1
select b;
LoadOperation<Beer> loBeers = _beerContext.Load(beerQuery);
grdLoadWithLinq.ItemsSource = loBeers.Entities;
Using DomainDataSource In Code
Normally, you will see the DomainDataSource class used declaratively in XAML. But we can also utilize a DDS through code and take advantage of its paging, filtering, sorting and grouping functions . Consider this code, which creates a DDS and executes the GetBeers query, only retreiving the Beers for BrewerId == 1. Note that only the records for BrewerId == 1 are sent from the server, because the DDS creates an appropriate query for any paging, filtering, sorting, or grouping functions.
DomainDataSource dsBeers = new DomainDataSource();
dsBeers.LoadSize = 30;
dsBeers.QueryName = "GetBeers";
dsBeers.AutoLoad = true;
dsBeers.DomainContext = _beerContext;
dsBeers.SortDescriptors.Add(new SortDescriptor("BeerName", System.ComponentModel.ListSortDirection.Ascending));
dsBeers.FilterDescriptors = new System.Windows.Data.FilterDescriptorCollection();
dsBeers.FilterDescriptors.Add(new System.Windows.Data.FilterDescriptor("BrewerId", System.Windows.Data.FilterOperator.IsEqualTo, 1));
grdLoadDomainDataSource.ItemsSource = dsBeers.Data;
dsBeers.Load();