I am getting started with Entity Framework using POCO in a model-first configuration. I have a slightly non-standard model - generated by customising the .tt file to respond to custom properties in the .edmx enabling me to trigger a NotifyPropertyChanged event for logging updates to certain properties - which results in a class that effectively looks a little like this:
public partial class MyClass: INotifyPropertyChanged
{
/// <summary>
/// Catches events to be added to the UserLog
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Notifies any event listeners attached to the PropertyChanged event that a loggable field
/// update has occurred.
/// </summary>
/// <param name="eventType">The type of the field.</param>
/// <param name="message">The message to record in the logs</param>
private void NotifyFieldUpdate(string eventType, string message)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new LogEventArgs(eventType, message));
}
}
private string _myField;
public virtual string MyField
{
get
{
return _myField;
}
set
{
if ( _myField != value )
{
_myField = value;
NotifyFieldUpdate( "FIELDCHANGE", String.Format("MyField changed to {0}", value) );
}
}
}
}
The event handler is then configured in another part of the partial class, to avoid unnecessary overwrites.
The problem I have is that if that gets updated twice, it falls over:
public void TestBehaviour(ObjectContext currentContext)
{
MyClass testMe = FetchFromObjectContext(currentContext);
testMe.MyField = "Hello";
currentContext.SaveChanges();
testMe.MyField = "Goodbye";
}
The moment I call the second of those methods, I hit the following error:
EntityMemberChanged or EntityComplexMemberChanged was called without first calling EntityMemberChanging or EntityComplexMemberChanging on the same change tracker with the same property name. For information about properly reporting changes, see the Entity Framework documentation.
I have tried using currentContext.DetectChanges()
and currentContext.Refresh( ... )
but that is really monkey coding as I don't know what exactly is going on.
My first question is: What is causing the problem and what do I have to do with the ObjectContext in order to avoid this type of error? It seems quite plausible to me that fields could be updated from time to time and I would hate for my system to fall over if it happened twice.
My second, perhaps more in-depth question is: Am I approaching this all wrong by using the INotifyPropertyChanged
interface when it appears that the class is firing these EntityMemberChanged
events already? I assume this is because the ObjectContext is creating a proxy- does that mean in some cases those methods are likely to be unavailable if I don't have my own notifications?