The ObjectStateManager already has an object with the same key. Multiple objects with the same key cannot be tracked by the ObjectStateManager.



In essence, I have a table with a few characteristics for a business. Their ID is utilized in several other tables since it is the "master" table. I essentially do this to find their ID:

private Company currentcompany()
        Company cuco = db.Companies.Single(x => x.username == User.Identity.Name);
        return cuco;

I needed to provide people the option to change different information about themselves that was kept in this database, which I accomplished flawlessly, but I discovered a significant security flaw!

I could quickly change the secret ID and alter the information for another company using Tamper Data on Firefox (and I suppose Fidler/many others).

I changed the edit action to include the following lines to prevent this:

        Company cuco = currentcompany();

        if ( !=
            return Content("Security Error");

(FYI -Company is a model/POCO speaking on behalf of a business, andcompany it is the form data itself.)

After adding this, if I change the ID in the form data, it behaves as anticipated and displays a "Security Problem," but if there isn't a security error and I continue, I get the error in the inquiry.

"In the ObjectStateManager, an object with the same key already exists. Multiple objects cannot be tracked by the ObjectStateManager using the same key."

I think EF is keeping track of and identifying the initial data pull in some way, but I'm not sure how to fix that.

Any suggestions?

edit- --update--

Is there a more effective method to get past this, if you understand what I'm attempting to accomplish?

5/17/2011 4:37:48 PM

Accepted Answer

You cannot connect an entity with the same key again after loading the entity from the context. The first entity is still kept in internal context cache and context can hold only one instance with given key value per type (it is called identity map and I've explained it here. in other situation).

Detaching the previous instance is one way to fix it, although you are not need to. You may use this if you simply need to store new values:

  • API for ObjectContext:context.YourEntitySet.ApplyCurrentValues(newEntity);
  • API DbContext:context.Entry(oldEntity).CurrentValues.SetValues(newEntity);
5/23/2017 12:26:29 PM

Popular Answer

Just a little assistance for you if you're unsure about where to lookoldEntity as said by Ladislav:

var entityKey = context.NewEntitySet.Create().GetType().GetProperty("Id").GetValue(newEntity);


Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow