如何在延迟加载的属性上引发 PropertyChanged 事件

How to raise PropertyChanged event on lazy loaded properties

所以我在实体和复杂类型之间有一个简单的关系,我想在复杂类型发生变化时通知实体,如这段代码所示

[Table("Bills")]
public class Bill : NotifyBase
{
    //how to call SetWithNotif when this changes ?
    public virtual Discount Discount { get; set; }

}

[ComplexType]
public class Discount : NotifyBase
{
   //some props in here  
}

 public class NotifyBase : INotifyPropertyChanged,INotifyPropertyChanging
 {       
    public void SetWithNotif<T>(T val,ref T field,[CallerMemberName] string prop = "" )
    {
        if (!field.Equals(val))
        {
            PropertyChanging?.Invoke(this, new PropertyChangingEventArgs(prop));
            field = val;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
        }
    }
    [field: NotMapped]
    public event PropertyChangedEventHandler PropertyChanged;
    [field: NotMapped]
    public event PropertyChangingEventHandler PropertyChanging;
}

哦,我刚刚意识到 virtual 意味着它可以有一个主体,幸运的是 EntityFramework 在它完成延迟加载后调用那个主体,所以这完美地工作了

[Table("Bills")]
public class Bill : NotifyBase
{
    //works !!
    private Discount m_Discount;
    public virtual Discount Discount
    {
        get { return m_Discount; }
        set { SetWithNotif(value, ref m_Discount); }
    }


}

[ComplexType]
public class Discount : NotifyBase
{
   //some props in here  
}

 public class NotifyBase : INotifyPropertyChanged,INotifyPropertyChanging
 {       
    public void SetWithNotif<T>(T val,ref T field,[CallerMemberName] string prop = "" )
    {
        if (!field.Equals(val))
        {
            PropertyChanging?.Invoke(this, new PropertyChangingEventArgs(prop));
            field = val;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
        }
    }
    [field: NotMapped]
    public event PropertyChangedEventHandler PropertyChanged;
    [field: NotMapped]
    public event PropertyChangingEventHandler PropertyChanging;
}