Hi all,

I know I haven’t posted for quite a while now, though I have been on a cool project doing some stuff with Azure, SQL Data Services, Silverlight 3 and countless other new technologies.

We are just about to finish our first iteration and there was something I struggled to find on the web: how to update an object in ADO.net Entity Framework.

I spent a long time looking around to see if there

was an “update” method, but every time I had the model context complaining (rightly so) about the object already being tracked and a need to detach it.  Another way was to give the strong typed object, find the related live object, detach that and then attach the new object (not pretty at all) and there was a problem that the newly attached object was in an “unmodified” state even if it was different… therefore would not commit the changes to the database on save.

The solution I found was to use the context’s ApplyPropertyChanges method with the object then SaveChanges on the context and the data is written back to the database.

msdn library on Apply Property Changes

public User UpdateUser(User user)
{
   if (user != null)
   {
      try
      {
         this.userDataContext.ApplyPropertyChanges("User", user);
         this.userDataContext.SaveChanges();
      }
      catch (InvalidOperationException ex)
      {
         throw new InvalidOperationException("Error when trying to update the user", ex);
      }
   }
   return user;
}

In the sample above, the userDataContext property is the reference to my entities object and in the model I have a “User” class which models a user’s preferences which I pass to a remote client (silverlight 3) which updates the object and sends it back on save.

Short post today, but hopefully helpful if anyone is struggling to do what I was.