如何发起有关财产变更的事件?

发布于 2024-10-31 11:30:37 字数 116 浏览 2 评论 0原文

当我使用 DataSet 时,有可能在 RowChanging、RowChanged、ColumnChanging、ColumnChanged 等上引发事件...

如何对实体框架中的实体执行相同的操作?

When I use DataSet, there is possiblity to raise events on RowChanging, RowChanged, ColumnChanging, ColumnChanged, etc...

How to do the same with an entity from Entity Framework ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

晚风撩人 2024-11-07 11:30:37

实体已经实现了 PropertyChanged 事件,因为它们实现了 System.ComponentModel.INotifyPropertyChanged。如果您想了解您的实体的变化,您只需订阅即可。

另请注意,实体支持以下两个部分方法(其中第二个方法应为您提供相当于“RowChanging”的功能),如果您想响应类内的更改,则可以重写它们:

protected override void OnPropertyChanged(string property) {}

protected override void OnPropertyChanging(string property) {}

Entities already implement the PropertyChanged event since they implement System.ComponentModel.INotifyPropertyChanged. If you want to catch changes to your entieis, you can just subscribe to that.

Also note that entities support the following two partial methods—the second of which should give you the equivalent of "RowChanging"—that you can override if you'd like to respond to changes within your class:

protected override void OnPropertyChanged(string property) {}

protected override void OnPropertyChanging(string property) {}
晨曦慕雪 2024-11-07 11:30:37

您可以执行以下操作来引发 Entity Framework 中属性更改的事件: 假设您有 Pubs 数据库 - 它有一个表 employee ,其中表结构如下:

pubs 数据库中的表员工

现在我们要跟踪属性 hire_date 的任何更改。您可以按照以下方式执行此操作(此示例可以在 LinqPad 中轻松使用 - 您只需定义 EF 数据源,然后就可以运行该示例):

void Main()
{
    var test=new employee();
    test.PropertyChanged += HandleSomethingHappening;
    test.hire_date = DateTime.Now;
}

public void HandleSomethingHappening(object sender, EventArgs e)
{
    var propName=((System.ComponentModel.PropertyChangedEventArgs)e).PropertyName;
    var empObj=(employee)sender;
    if (propName=="hire_date")
    {
        Console.WriteLine(propName+" changed to: " + empObj.hire_date.Date.ToString("d"));
    }
}

如果运行它,它将显示

雇用日期已更改:2015 年 9 月 17 日

雇用日期已更改:控制台上的

test.hire_date = DateTime.Now;

,因为在主方法中我们通过以下方式更改了属性: NB

  • 要删除事件注册,您可以使用:
    test.PropertyChanged - = HandleSomethingHappening;
  • 此处所示,也允许使用 Lambda;例如,您可以使用:
    test2.PropertyChanged +=
    (c, a) =>; Console.WriteLine(((System.ComponentModel.PropertyChangedEventArgs)a).PropertyName + "员工实体中的属性已更改");

    它将处理与上面示例相同的事件。但在这种情况下,取消注册是不可能的,因为您无法引用隐式创建的匿名函数
  • 您也可以使用 PropertyChanging 事件,该事件将在更改之前触发 这不仅
  • 限于实体框架,您可以在每个类中使用它,如这篇文章所示。

高级提示:

如果您想更好地了解幕后发生的事情,我提供了 employee 类的简化代码(仅包含运行所需的属性和事件)上面的示例):

public class employee //: EntityObject
{


    #region Primitive Properties

    public global::System.DateTime hire_date
    {
        get
        {
            return _hire_date;
        }
        set
        {
            //Onhire_dateChanging(_hire_date);
            _hire_date=value;
            Onhire_dateChanged();
        }
    }
    private DateTime _hire_date;


    void Onhire_dateChanged()
    {
            var handler = this.PropertyChanged; // copy before access (to aviod race cond.)
            if (handler != null)
            {                   
                var args=new PropertyChangedEventArgs() { PropertyName="hire_date" };
                handler(this, (System.EventArgs)args);
            }
    }

    public event EventHandler PropertyChanged;

    #endregion

}


public class PropertyChangedEventArgs: System.EventArgs
{
    public string PropertyName  { get; set; }
}

您可以看到事件是如何连接的 - 它在属性的 set 方法中触发。

You can do the following to raise an event on property changed in Entity Framework: Suppose you have the Pubs database - it has a table employee with the following table structure:

Table employee in pubs database

Now we want to track any changes of the property hire_date. You can do it the following way (this example can be used easily in LinqPad - you just need to define a EF datasource and then you can run the example):

void Main()
{
    var test=new employee();
    test.PropertyChanged += HandleSomethingHappening;
    test.hire_date = DateTime.Now;
}

public void HandleSomethingHappening(object sender, EventArgs e)
{
    var propName=((System.ComponentModel.PropertyChangedEventArgs)e).PropertyName;
    var empObj=(employee)sender;
    if (propName=="hire_date")
    {
        Console.WriteLine(propName+" changed to: " + empObj.hire_date.Date.ToString("d"));
    }
}

If you run it, it will show

Hire date changed: 17.09.2015

on the console, because in the main method we changed the property via:

test.hire_date = DateTime.Now;

N.B.

  • To remove the event registration, you can use:
    test.PropertyChanged -= HandleSomethingHappening;
  • As shown here, Lambdas are also allowed; e.g. you could use:
    test2.PropertyChanged +=
    (c, a) => Console.WriteLine(((System.ComponentModel.PropertyChangedEventArgs)a).PropertyName + " property has changed in employee entity");

    which would handle the same event as the example above. But in this case, de-registration is not possible since you cannot refer to the anonymous function implicitly created
  • You can use the PropertyChanging event as well, which will trigger before the change is happening
  • This is not limited to the Entity Framework, you can use it in every class as this SO article shows.

Advanced hints:

If you want to understand better what is going on behind the scenes, I am providing a simplified code of the employee class (just the property and event needed to run the example above):

public class employee //: EntityObject
{


    #region Primitive Properties

    public global::System.DateTime hire_date
    {
        get
        {
            return _hire_date;
        }
        set
        {
            //Onhire_dateChanging(_hire_date);
            _hire_date=value;
            Onhire_dateChanged();
        }
    }
    private DateTime _hire_date;


    void Onhire_dateChanged()
    {
            var handler = this.PropertyChanged; // copy before access (to aviod race cond.)
            if (handler != null)
            {                   
                var args=new PropertyChangedEventArgs() { PropertyName="hire_date" };
                handler(this, (System.EventArgs)args);
            }
    }

    public event EventHandler PropertyChanged;

    #endregion

}


public class PropertyChangedEventArgs: System.EventArgs
{
    public string PropertyName  { get; set; }
}

You can see how the event is wired up - it gets triggered in the property's set method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文