EFMVC error updating and solution

I was attempting to update a record using EFMVCs default “Update()” function from EFMVC and came across the following error:

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

The solution was to rewrite the Update function as such:

Code Snippet
  1. publicvirtualvoid Update(T entity)
  2. {
  3.     if (entity == null)
  4.     {
  5.         thrownewArgumentException(“Cannot add a null entity.”);
  6.     }
  7.     var entry = dataContext.Entry<T>(entity);
  8.     if (entry.State == EntityState.Detached)
  9.     {
  10.         var set = dataContext.Set<T>();
  11.         string keyName = dbset.Create().GetType().GetProperties().Single(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Count() > 0).Name;
  12.         var pkey = dbset.Create().GetType().GetProperty(keyName).GetValue(entity);
  13.         T attachedEntity = set.Find(pkey);  
  14.         if (attachedEntity != null)
  15.         {
  16.             var attachedEntry = dataContext.Entry(attachedEntity);
  17.             attachedEntry.CurrentValues.SetValues(entity);
  18.         }
  19.         else
  20.         {
  21.             entry.State = EntityState.Modified;
  22.         }
  23.     }
  24.     // ORIGINAL CODE
  25.     //dbset.Attach(entity);
  26.     //dataContext.Entry(entity).State = EntityState.Modified;
  27. }

I took the advice of this post:
http://stackoverflow.com/questions/12585664/an-object-with-the-same-key-already-exists-in-the-objectstatemanager-the-object

but it required changing a bit more code than I wanted (adding an interface to each entity), so I added the following code to find the primary key of an entity

Code Snippet
  1. string keyName = dbset.Create().GetType().GetProperties().Single(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Count() > 0).Name;
  2. var pkey = dbset.Create().GetType().GetProperty(keyName).GetValue(entity);

In the future, I’ll add some more logic for when entities do NOT have primary keys, but for my architecture all tables will.

Posted in api, asp.net, coding

Leave a Reply

Your email address will not be published. Required fields are marked *

*