如何发起有关财产变更的事件?
当我使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实体已经实现了
PropertyChanged
事件,因为它们实现了System.ComponentModel.INotifyPropertyChanged
。如果您想了解您的实体的变化,您只需订阅即可。另请注意,实体支持以下两个部分方法(其中第二个方法应为您提供相当于“RowChanging”的功能),如果您想响应类内的更改,则可以重写它们:
Entities already implement the
PropertyChanged
event since they implementSystem.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:
您可以执行以下操作来引发 Entity Framework 中属性更改的事件: 假设您有 Pubs 数据库 - 它有一个表
employee
,其中表结构如下:现在我们要跟踪属性
hire_date
的任何更改。您可以按照以下方式执行此操作(此示例可以在 LinqPad 中轻松使用 - 您只需定义 EF 数据源,然后就可以运行该示例):如果运行它,它将显示
雇用日期已更改:控制台上的
,因为在主方法中我们通过以下方式更改了属性: NB
test.PropertyChanged - = HandleSomethingHappening;
test2.PropertyChanged +=
(c, a) =>; Console.WriteLine(((System.ComponentModel.PropertyChangedEventArgs)a).PropertyName + "员工实体中的属性已更改");
它将处理与上面示例相同的事件。但在这种情况下,取消注册是不可能的,因为您无法引用隐式创建的匿名函数
PropertyChanging
事件,该事件将在更改之前触发 这不仅高级提示:
如果您想更好地了解幕后发生的事情,我提供了
employee
类的简化代码(仅包含运行所需的属性和事件)上面的示例):您可以看到事件是如何连接的 - 它在属性的
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: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):If you run it, it will show
on the console, because in the main method we changed the property via:
N.B.
test.PropertyChanged -= HandleSomethingHappening;
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
PropertyChanging
event as well, which will trigger before the change is happeningAdvanced 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):You can see how the event is wired up - it gets triggered in the property's
set
method.