I am having some trouble with data binding and the Entity Framework’s navigation properties.
I have two classes, generated by the Entity Framework designer:
Class Foo:
id (int)
bar (Bar)
...
Class Bar
id (int)
name (string)
...
Using an ObservableCollection<Foo>, I have populated a datagrid with the following columns:
<DataGrid.Columns>
<DataGridTextColumn Header="Id" Binding="{Binding Path=id}"/>
<DataGridTemplateColumn Header="Bar">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox
SelectedValuePath="Id"
SelectedValue=
"{Binding Path=bar.Id, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="name"
ItemsSource=
"{Binding Path=BarList,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Window}}}"
Background="White" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
The ComboBox is populated with an ObservableCollection<Bar> and is correctly showing the current Bar.
The problem comes when I select another item in the combobox. I get the following error:
System.Windows.Data Error: 8 : Cannot save value from target back to source.
System.InvalidOperationException: The property 'Id' is part of the object's key information and cannot be modified
I can see why the error pops up, but how can I handle this differently?
EDIT: The relationship between Foo and Bar is N..1, meaning that a Foo has 1 or 0 Bar while a Bar can have several Foos.
At the moment, I am not able to select a new Bar for my Foos.
You have to bind on the
barproperty directly. Your code tries to change theIdon the selected Foo’s bar, but what you want is to change the bar associated to the current Foo. You also have to overrideEqualsmethod on yourBarclass.And in your
Barclass :