views:

234

answers:

1

I have two tables in the model, one table contains entries related to the other table in a one to many relations, for example:

Table User
  ID
  Name

Table Comments
  ID
  UserID
  Title
  Text

I want to show a datagrid in a WPF window with two columns, one text column with the User name and another column with a combobox showing all the comments made by the user.

The datagrid definition is like this:

        <DataGrid AutoGenerateColumns="False" [layout options...] Name="dataGrid1" ItemsSource="{Binding}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}"/>
            <DataGridComboBoxColumn Header="Comments"
                SelectedValueBinding="{Binding Path=UserID}"
                SelectedValuePath="ID"
                DisplayMemberPath="Title"
                ItemsSource="{Binding Path=Comments}"
                />
        </DataGrid.Columns>
    </DataGrid>

in the code I assign the DataContext like this:

dataGrid1.DataContext = entities.Users;

The entity User has a property named Comments that leads to all the comments made by the user. The queries are returning data and the user names are shown but the combobox is not being filled.

May be the approach is totally wrong or I'm just missing a very simple point here, I'm opened to learn better methods to do this.

Thanks

A: 

I have actually already used your approach. It works, but with a caveat: the combobox can only show the current item for a given object if it is in its list of allowed values (here entities.Users).

You'll say "yes, but it is! I've put in the whole Users list". Sadly, it isn't. The default comparison for entites in the EF is not based on EntityKeys (my guess is it's the default comparison, i.e. reference comparison), so in the object you've got a reference to one object, abd in the list you've got a reference to another (with the same EntityKey for both).

My solution is to override the comparison function for User class, with a simple check of ID==ID. Note I'm not saying this is the best approach (it may have unwanted consequences in the rest of your code, for example), just that it worked well for me.

Oh, and a general recommendation is not to bind directly controls to IQueriables, but to the result of the Execute function (or else the query will be run twice against the database), see msdn for more details.

Marcanpilami