I’m building WPF app, and I got to the point where I want to be able to check whether an entity IsDirty, so I found this solution online:
private bool isDirty;
public virtual bool IsDirty
{
get { return isDirty; }
set { isDirty = value; }
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
OnPropertyChanged(true, propertyName);
}
protected void OnPropertyChanged(bool makeDirty, [CallerMemberName] string propertyName = "")
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
if (makeDirty)
{
isDirty = makeDirty;
}
}
Then I can use it like this
[Required(ErrorMessage = ErrorMessages.DescriptionRequired)]
[StringLength(60, ErrorMessage = ErrorMessages.DescriptionLength60)]
public string Description
{
get { return description; }
set
{
if (description != value)
{
description = value;
OnPropertyChanged();
}
}
}
And it seems to work, anytime a property is changed the entity will get dirty because OnPropertyChanged is called. The problem I have is when I load an entity (or collection of entities) from a database, then onpropertychanged is called:
SomeEntitiesCollection = new Service().SomeEntities();
Then each entity which comes is marked as dirty, and I cannot find anyway around it, apart from going through a loop and setting IsDirty back to false. Is there anyother way of achieving it?
Regards
no, there isn't an easy way
you should override your method that retrieve entities from db in a way that it sets automatically
Isdirty=false
on entity creation. I used nhibernate interceptor and events to do something similar but it is not your case.another way is to keep a copy of all the original values and compute the dirtiness when anyone asks for it. So instead of using a isdirty property you should create a method and save an initial state for all properties