Saturday 12 November 2011

Display Child data with Parent from different tables in Silverlight Datagrid

Let us describe the problem, we have two tables:

 ParentTable
  FatherID, FatherName

 ChildTable
  ChildID, ChildName, FatherId

Now in DomainService.cs the GetChildTable() query looks like:

        public IQueryable<ChildTable> GetChildTable()
        {
            return this.ObjectContext.ChildTable;
        }

and when we bind FatherName with ChildName in XAML we don't see FatherName as we expect.

            <sdk:DataGrid  x:Name="dgFamily" AutoGenerateColumns="False">
                <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Header="Child name" Binding="{Binding Path=ChildName}" />
                <sdk:DataGridTextColumn Header="Father name" Binding="{Binding Path=FatherTable.FatherName}" />

This is due to Domain Service does not include the FatherTable with ChildTable in the GetChildTable() query, unless we ask for it.

We have to edit the DomainService.cs file and use the 'Include' in our query as:

        public IQueryable<ChildTable> GetChildTable()
        {
            return this.ObjectContext.ChildTable.Include("FatherTable");
        }

Also, if we look at the Metadata file: DomainService.metadata.cs it will look like:

        internal sealed class ChildTableMetadata
        {
            private ChildTableMetadata()
            {
            }
            public FatherTable FatherTable { get; set; }

We need to update and add the '[Include]' before the FatherTable public property, as:

        internal sealed class ChildTableMetadata
        {
            private ChildTableMetadata()
            {
            }
            [Include]
            public FatherTable FatherTable { get; set; }

Now, test you binding..
It is working

No comments:

Post a Comment