Note that there are some explanatory texts on larger screens.

plurals
  1. POEntity Framework Code-First: "The ObjectStateManager cannot track multiple objects with the same key."
    primarykey
    data
    text
    <p>I'm running into an issue with Entity Framework code-first in MVC3. I'm hitting this exception:</p> <blockquote> <p>An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.</p> </blockquote> <p>This is addressed many times on SO, but I'm having trouble utilizing any of the suggested solutions in my situation.</p> <p>Here is a code sample:</p> <pre><code>FestORM.SaleMethod method = new FestORM.SaleMethod { Id = 2, Name = "Test Sale Method" }; FestContext context = new FestContext(); //everything works without this line: string thisQueryWillMessThingsUp = context.SaleMethods.Where(m =&gt; m.Id == 2).Single().Name; context.Entry(method).State = System.Data.EntityState.Modified; context.SaveChanges(); </code></pre> <p><em>EDITED to clarify:</em> I am attempting to update an object that already exists in the database.</p> <p><strong>Everything works fine without the query noted in the code.</strong> In my application, my controller is instantiating the context, and that same context is passed to several repositories that are used by the controller--so I am not able to simply use a different context for the initial query operation. I've tried to remove the entity from being tracked in the ObjectStateManager, but I can't seem to get anywhere with that either. I'm trying to figure out a solution that will work for both conditions: sometimes I will be updating an object that is tracked by the ObjectStateManager, and sometimes it will happen to have not been tracked yet.</p> <p>FWIW, my real repository functions look like this, just like the code above:</p> <pre><code>public void Update(T entity) { //works ONLY when entity is not tracked by ObjectStateManager _context.Entry(entity).State = System.Data.EntityState.Modified; } public void SaveChanges() { _context.SaveChanges(); } </code></pre> <p>Any ideas? I've been fighting this for too long...</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload