Update Entity Framework property when different property in model is changed
asp.net-mvc-4, c#, entity-framework, inotifypropertychanged, observablecollection
Solution
NotfiyPropertyChanged will only called when you set the whole collection and not the included items.
This is a workaround for the problme:
public partial class Product : INotifyPropertyChanged
{
public Product()
{
this.Designs = new ObservableCollection<Design>();
this.Designs.CollectionChanged += ContentCollectionChanged;
}
public void ContentCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
// This will get called when the collection is changed
// HERE YOU CAN ALSO FIRE THE PROPERTY CHANGED
}
public int BookingProductId { get; set; }
public System.Guid BookingId { get; set; }
public decimal Price { get; set; }
public virtual Booking Booking { get; set; }
public virtual ObservableCollection<Design> Designs { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Problem
I have an Entity Framework model ``` public partial class Product { public Product() { this.Designs = new HashSet<Design>(); } public int BookingProductId { get; set; } public System.Guid BookingId { get; set; } public decimal Price { get; set; } public virtual Booking Booking { get; set; } public virtual ICollection<Design> Designs { get; set; } } ``` ...in which I would like to update the Price property in response to a new Design being added to the Product. I've tried to follow this example: How can I change an Entity Framework ICollection to be an ObservableCollection? so my class reads as follows: ``` public partial class Product : INotifyPropertyChanged { public Product() { this.Designs = new ObservableCollection<Design>(); } public int BookingProductId { get; set; } public System.Guid BookingId { get; set; } public decimal Price { get; set; } public virtual Booking Booking { get; set; } public virtual ObservableCollection<Design> Designs { get; set; } public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "") { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } ``` but if I add a new Design to the Product as so ``` product.Designs.Add(new Design()); ``` then the NotifyPropertyChanged method is never fired. Does anyone know why??? Thanks in advance