LINQ to ADO.NET—INotifyPropertyChanging Interface
The INotifyPropertyChanging Interface
By opening up the code produced by the SQLMetal tool, we can see some
minor differences between it and the code we wrote. There are four types
of constructor accepting different connection attributes, such as a
connection string and an IDBConnection object, but the big difference is the
use of the INotifyPropertyChanging and INotifyPropertyChanged:
[Table(Name="Person")] public partial class Person : INotifyPropertyChanging, INotifyPropertyChanged { private int _ID;
Both the INotifyPropertyChanging interface and the INotifyPropertyChanged
interface are in the System.ComponentModel namespace. Both interfaces
require two events:
public event PropertyChangedEventHandler PropertyChanging; public event PropertyChangedEventHandler PropertyChanged;
They also require virtual methods to handle the interfaces:
protected virtual void SendPropertyChanging() { if ((this.PropertyChanging != null)) { this.PropertyChanging(this, emptyChangingEventArgs); } } protected virtual void SendPropertyChanged (string propertyName) { if ((this.PropertyChanged != null)) { this.PropertyChanged (this, new PropertyChangedEventArgs(propertyName)); } }
The emptyChangingEventArgs field is a private static class’s field defined in
the class as an object of the PropertyChangingEventArgs class created
providing an empty string as parameter. In the generated code, each set
accessor of a column calls two methods. The SendPropertyChanging method
is called just before the variable is set to the provided value. The
SendPropertyChanged method is called just after the variable is set.
[Column(Storage="_ID", AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)] public int ID { get { return this._ID; } set { if ((this._ID != value)) { this.OnIDChanging(value); this.SendPropertyChanging(); this._ID = value; this.SendPropertyChanged("ID"); this.OnIDChanged(); } } } }
Note Since the column is the IDENTITY type, the SQLMetal adds the AutoSync attribute to refresh column’s value when a new record is inserted.
The use of INotifyPropertyChanging and INotifyPropertyChanged is not
mandatory. In fact, the code we wrote works very well. But these interfaces
help LINQ change tracking. The SendPropertyChanging and
SendPropertyChanged methods significantly improve change tracking
because LINQ doesn’t have to check changes manually. If you don’t use these two interfaces and you don’t inform LINQ about row changes, it will
use two copies of the same object to understand if something is changed.
There will be two objects representing each table, wasting memory and
cycles when you call SubmitChanges().
|

