I’m currently working with the .NET RIA Services SDK with Silverlight 3 for getting and modifying data from the server using LINQ. Now there are a ton of samples and blog posts available that show you how to work with data from the server. However, one thing in common with all these posts is that they usually work with only one table at a time. What if you want to show the result of a join on the table? This is where a relatively unknown feature called the IncludeAttribute comes in. Let’s take an example for this to explain it in detail.
Let’s take the example with the simple Northwind
database and use the Product-Supplier-Category relationship in the LINQ/EF designer. Now I assume you have already created the DomainService class along with the associated metadata buddy class for all the entities. At this point I don’t really care whether the add/edit/delete functionality is on or not.
What is important are the two class files. And this is where the IncludeAttribute directive comes very handy. First open up the metadata class and in the Product entity add the directive: [Include] above each of the members that point to the other entities. For instance:
[Include]
public Category Category;
...
[Include]
public Supplier Supplier;
Now open the main domain service class and change the GetProducts method to look like this:
public IQueryable<Product> GetProducts()
{
DataLoadOptions loadOpts = new DataLoadOptions();
loadOpts.LoadWith<Product>(p => p.Category); // Load the Cateogry
loadOpts.LoadWith<Product>(p => p.Supplier); // Load the Supplier
this.Context.LoadOptions = loadOpts;
var q = from p in this.Context.Products
orderby p.ProductName
select p;
return q;
}
Finally, to display the associated elements in say a DataGrid use the following in the Silverlight MainPage.xaml page:
<data:DataGrid x:Name="dgData" AutoGenerateColumns="False">
<data:DataGrid.Columns>
<data:DataGridTextColumn Header="Product Name"
Binding="{Binding ProductName}" />
<data:DataGridTextColumn Header="Supplier"
Binding="{Binding Supplier.CompanyName}" />
<data:DataGridTextColumn Header="Category"
Binding="{Binding Category.CategoryName}" />
</data:DataGrid.Columns>
</data:DataGrid>
Note the dot-separated naming convention.
This allows the client to load and point to the right record in the child table like what is shown on the left.
Hope this helps you in quickly using data from child tables easily in your Silverlight 3 RIA applications.
Tags:
silverlight,
tips,
development
Categories:
Development |
Tips |
SilverLight