Silverlight - merging detached object back to the attached data context

This is a short post on something that we did in the days of Silverlight 2~3, before we have RIA services.

Consider two method signatures on the service:

  1. public EntityPerson GetPerson(object key);
  2. public void SavePerson(EntityPerson person);

Silverlight gets an EntityPerson object, exposes it via the ViewModel for databinding.  The user hits the save button, and the data is coming back through the wire.

It comes back to SavePerson, but the object is disconnected.

The way we've always done this is this way:

//Update or Insert person:
if (entityPerson.PersonID > 0) //update 
    EntityKey key = entities.CreateEntityKey("tblPerson", entityPerson);
    object originalItem;
    if (entities.TryGetObjectByKey(key, out originalItem))
        // merge changes from the client back to the dataset
        entities.ApplyPropertyChanges(key.EntitySetName, entityPerson);
else//insert new 
    entities.AddObject("tblPerson", entityPerson);

ApplyPropertyChanges works very well and takes a lot of the work out of our hands.  You can attach a very simple conflict detection if you have a Timestamp field, and by setting the ConcurrencyMode=Fixed.

Saving Changes and Managing Concurrency
How to: Manage Data Concurrency in the Object Context
Flexible Data Access With LINQ To SQL And The Entity Framework

I was recently involved in a short discussion on this topic, and was intrigued to go digging and get to the bottom of it all.  Hope these links help someone :-)