DLinq Object Tracking and INotifyPropertyChanging - PropertyChanging Event

DLinq Object Tracking and INotifyPropertyChanging - PropertyChanging Event

by David Hayden ( C# .NET Developer )

Filed: LINQ, O/R Mappers

 

As I spend more time with DLinq, it becomes more and more apparent that one really has to use SqlMetal to create the DLinq entities because there is more going on in these classes than meets the eye.

When you generate the entities using SqlMetal, you will notice that each object implements an INotifyPropertyChanging Interface. Here is a snippet of the Genre class in my previous example:

 

public partial class Genre :
System.Data.DLinq.INotifyPropertyChanging ...
public event System.ComponentModel.
PropertyChangedEventHandler PropertyChanging;
protected virtual void
OnPropertyChanging(string PropertyName) { if ((this.PropertyChanging != null)) { this.PropertyChanging(this,
new PropertyChangedEventArgs(PropertyName)); } }

 

DLinq apparently looks to see if your entities implement the INotifyPropertyChanging Interface to determine how to track changes.

If your DLinq entities don't implement INotifyPropertyChanging Interface, DLinq makes a copy of them internally the first time it finds out about them. When you then call SubmitChanges on the DataContext Class, it will do a comparison of the real object with it's internal copy to determine if and what changes need to occur to the underlying database. Thus, if you don't implement the INotifyPropertyChanging Interface, two copies of each object will exist in memory.

If your Dlinq entities do implement INotifyPropertyChanging Interface, the DataContext Class merely subscribes to the PropertyChanging Event for each entity as opposed to creating another copy of it internally. This sounds like it will not only save you the memory overhead of DLinq creating twice the entities, but also save you a performance hit of DLinq comparing each entity with its original during the SubmitChanges process.

If you want to take advantage of the more intelligent entity tracking service offered by DLinq, you will of course need to implement the interface appropriately as well as call the OnPropertyChanging method each time a property / field changes on your entities like below:

 

public string Name {
get {
  return this._Name;
}
set {
  if ((this._Name != value)) {
    this.OnPropertyChanging("Name");
    this._Name = value;
    this.OnPropertyChanged("Name");
  }
}
}

 

Not that we write such repetitive and monotonous code by hand anyway, but it certainly gives you something to think about if you think you can create these DLinq entities by hand without the need for SqlMetal or a similar code generator.

File: LINQ, O/R Mappers

Source: David Hayden ( C# .NET Developer )

 

posted on Saturday, May 20, 2006 10:25 AM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices