Search code examples
c#entity-frameworkbindingupdatingnavigation-properties

Navigation Property not updating after SaveChanges EF 4.1


Im trying to update a NavigationProperty of a single entity object but its not updating after SaveChanges.

It only works when the object entity is not bound to any UI element through a property, i mean, if I bind a property to the UI, and change a navigatio property, the property is changed normally but its not updating on database.

Before trying to do it via binding it was working perfectly...

Code:

public TProd_NCMProd ItemAt
    {
        get { return itemAt; }
        set
        {
            itemAt = value;
            OnPropertyChanged(new PropertyChangedEventArgs("ItemAt"));
        }
    }
...
...
...
private void save()
    {
            //ItemAt.TProd_NCMGrupo is my navigation property
            ItemAt.TProd_NCMGrupo = ((TProd_NCMGrupo)cb_ncmGrupo.SelectedItem);

            itemAtBo.update(ItemAt);
            itemAtBo.saveChanges();
    }
...

The Update and Savechanges methods (DAO layer):

 public void update(T pEntity)
    {
        entidades.ApplyCurrentValues<T>(pEntity.GetType().Name, pEntity);
    }

 public void saveChanges()
    {
        entidades.SaveChanges();
    }

Solution

  • Instead of manually setting the reference

    ItemAt.TProd_NCMGrupo = ((TProd_NCMGrupo)cb_ncmGrupo.SelectedItem);
    

    I just set the combobox to be bound to the navigation property of my ItemAt->TProd_NCMGrupo so when I change the combobox selection, the navigation property changes too.

    Xaml

    <combobox ItemsSource="{Binding ItemsCb}" SelectedItem="{Binding Path=ItemAt.TProd_NCMGrupo, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}">
    ...
    </combobx>