Tuesday, October 30, 2012

Windows Phone's LinqToSql flakyness


I started doing Windows Phone development with Mango, which comes with SqlCe + LinqToSql. I had a lot of experience building WPF and Silverlight applications LinqToSql and Entity Framework against SQL Server, so I thought it all should be the same, or pretty close.
I started coding away and pretty soon realized some of the database operations, such as updates and deletes, were not working. I would have one update/SubmitChanges and, right after, re-query the entity and realized no changes were saved.
INotifyPropertyChanged was properly implemented, everything appeared to be ok.

I finally found out the culprit: lack of INotifyPropertyChangING on all properties of the table.

Yes, make sure to call your NotifyPropertyChanging before the assignment in the setter, and NotifyPropertyChanged afterwards. Something like this:

private DateTime startDateTime;
[Column]
public DateTime StartDateTime
{
    get { return startDateTime; }
    set
    {
        NotifyPropertyChanging("StartDateTime"); 
        startDateTime = value;
        NotifyPropertyChanged("StartDateTime");
    }
}

Here is my implementation of the two handlers for your convenience. This is not production-worthy because of lack of type-checking on the property name, but it's ok for illustrating my point:

public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(String propertyName)
{
    var handler = PropertyChanged;
    if (null != handler)
    {
        handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

public event PropertyChangingEventHandler PropertyChanging;
public void NotifyPropertyChanging(string propertyName)
{
    var handler = PropertyChanging;
    if (null != handler)
    {
        handler(this, new PropertyChangingEventArgs(propertyName));
    }
}