I have a custom base type called MyEntityBase for the superclass of the types in my auto-generated DataContext class, MyContext. In attempting to create a mock data context, I decided to implement INotifyPropertyChanged on MyEntityBase so I can generically track changes.
Here’s what my class looks like:
public abstract class MyEntityBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
}
Based on this class, I have created a generic Repository<T> class for storing instances of a specific type of entity. The basic idea behind this class is to provide methods similar to a datacontext, but instead backed by an in-memory list. I also want to simulate tracking changes, since the change set is important to the business logic of our application for syncing with 3rd-party systems.
Here is a basic shell implementation of Repository<T>:
public class Repository<T>
where T : MyEntityBase, INotifyPropertyChanged
{
protected List<T> _data;
public Repository(List<T> data)
{
this._data = data;
foreach (var entity in this._data)
{
entity.PropertyChanged += new PropertyChangedEventHandler(entity_PropertyChanged);
}
}
protected void entity_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Console.WriteLine("HERE");
}
}
Now I create a simple repository of type Employee, populate some data, and attempt to modify properties of the data. I would expect that the PropertyChanged event is raised since the Employee object has property-change notification built-in from the auto-generated DataContext. However, when I run the following code, I do not see HERE generated in the output anywhere:
var data = new List<Employee> {
new Employee { FirstName = "Bob" },
new Employee { FirstName = "Joe" },
};
var repo = new Repository<Employee>(data);
// This should fire the PropertyChanged event
data[0].FirstName = "John";
What am I doing wrong?
Update: If I change the line that subscribes to the event to the following:
(entity as Employee).PropertyChanged += ...
Then it works fine. However, T is already known to be Employee and entity is an instance of type Employee, so what’s the difference? Even if I make the event in MyEntityBase to be virtual, it still doesn’t work properly.
I have a workable solution implemented, so I will answer my own question. Since I already have a command-line tool
FindAndReplaceText.exethat I use to do some customizations to the auto-generatedMyDataContext.dbmlfile, I just added another call at the end where I modify all events in the generatedMyDataContextclass to includeoverride. Coupled with making my base class usevirtualin the definitions of the events, this solves the problem:Now the property changes notify properly in my test code.