实体框架4.1为POCO对象实现INotifyPropertyChanged

时间:2013-05-06 18:30:33

标签: entity-framework ef-code-first poco

我首先实现代码,MVC模式和使用Entity Framework 4.1。我把问题用粗体。

让我们假设(为了简化)我有以下POCO对象(Department),我想知道一旦contextDB.SaveChanges()进行更改它何时更改并更新它,所以我实现了以下内容:

public class Department : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
        if (propertyChanged != null)
        {
            propertyChanged(this, e);
        }
    }

    [Key(), Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

    private string name;

    [Required]
    public string Name
    {
        get
        {
            return this.name;
        }

        set
        {
            if (this.name== value)
            {
                return;
            }

            this.name= value;
            this.NotifyPropertyChanged(this, new PropertyChangedEventArgs("Name"));
        }
    }

    private string personInCharge;

    [Required]
    public string PersonInCharge
    {
        get
        {
            return this.personInCharge;
        }

        set
        {
            if (this.personInCharge== value)
            {
                return;
            }

            this.personInCharge= value;
            this.NotifyPropertyChanged(this, 
                    new PropertyChangedEventArgs("PersonInCharge"));
        }
    }
}

我有3个项目(类库),M(模型),V(视图)和C(控制器)。

从视图(V),用户生成和事件,例如,通过按下按钮添加一个部分,以便参考控制器(C)的视图在控制器中调用方法“添加”。

引用模型(M)的控制器(C)可以访问上下文,因为它实例化了从模型中的dbContext派生的类,并通过上下文通过例如dbContext更新实体“Department”。 departments.add(newDepartment)。

当在模型中更新实体部门时,上面在实体部门中描述的NotifyPropertyChanged被引发但我的问题从这里开始并且是:如何对View说,嘿!实体部门已经改变,因此应该更新视图部门!

为了实现它,我实现了观察者模式,我的意思是视图部门有一个名为“更新”的方法,附加到由模型维护的观察者集合,因此模型在属性更改时会迭代每个视图和视图更新的集合和调用方法“更新”。

我的问题是:我不知道如何从视图中订阅上述类部门中的事件PropertyChanged,以便在Department POCO对象(上面描述的类)中更改属性后,模型迭代在包含附加观察者的观察者集合上,然后为附加到集合的每个视图(观察者)调用适当的“更新”方法。或者它有另一种更好的方法来做,而不是使用INOTifyPropertyChanged用于POCO对象?

另外我看到使用INotifyPropertyChanged的问题,我的意思是,例如,每次添加depatment时,视图将更新两次,因为NotifyPropertyChanged被引发两次,一次来自Name属性,另一次来自PersonInCharge属性。这里的另一个问题是:如何只提高一次NotifyPropertyChanged事件而不是两次?

0 个答案:

没有答案