更改模型中的不同属性时更新实体框架属性

led*_*gon 5 c# entity-framework observablecollection inotifypropertychanged asp.net-mvc-4

我有一个实体框架模型

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; }
}
Run Code Online (Sandbox Code Playgroud)

...其中我想更新 Price 属性以响应添加到产品中的新设计。我试图按照这个例子:

如何将实体框架 ICollection 更改为 ObservableCollection?

所以我的课如下:

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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是如果我为产品添加一个新的设计

product.Designs.Add(new Design());
Run Code Online (Sandbox Code Playgroud)

那么 NotifyPropertyChanged 方法永远不会被触发。有谁知道为什么???

提前致谢

Bas*_*ili 3

仅当您设置整个集合而不是包含的项目时,NotfiyPropertyChanged 才会被调用。

这是该问题的解决方法:

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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)