【问题标题】:How to raise PropertyChanged event on lazy loaded properties如何在延迟加载的属性上引发 PropertyChanged 事件
【发布时间】:2017-09-05 05:41:24
【问题描述】:

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

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

【问题讨论】:

    标签: c# wpf entity-framework-6 lazy-loading inotifypropertychanged


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-28
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-26
      相关资源
      最近更新 更多