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

时间:2013-11-22 11:42:49

标签: c# entity-framework asp.net-mvc-4 observablecollection inotifypropertychanged

我有一个实体框架模型

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; }
}

...我希望更新Price属性以响应添加到产品中的新设计。我试过这个例子:

How can I change an Entity Framework ICollection to be an 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));
        }
    }
}

但如果我将新设计添加到产品中

product.Designs.Add(new Design());

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

提前致谢

2 个答案:

答案 0 :(得分:3)

NotifyPropertyChanged永远不会触发,因为向Designs集合中添加另一个元素实际上并不会更改任何Product的属性。如果要跟踪集合本身的更改,则应实现INotifyCollectionChanged接口。 ObservableCollection已经实现了,所以你可以简单地处理CollectionChanged事件。

答案 1 :(得分: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));
        }
    }
}