Note that there are some explanatory texts on larger screens.

plurals
  1. PONew ObjectContext throws ObjectStateManager exception
    text
    copied!<p>I'm Using WPF, .NET 4.0, and EF5. I want to keep the opened ObjectContexts on a minimum, so i use every object context in a using block.</p> <p>Regardless, when I execute the following code, the object context throw an exception, saying, that "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key"</p> <p>How is this possible? My ObjectContext is brand new, and I only attach one entity (Note: Both entity 1 and 2 exists in the database). I tried to search for an answer, but all the examples that i found about this type of question are not have a using bock.)</p> <pre><code>public class Foo{ public int Id{get;set;} public string Bar{get;set;} } public void Bar(Foo foo){ using(var ctx = new MyContext()){ ctx.Foos.Attach(foo); //Throws ObjectStateManager exception, at 2nd call foo.Bar = "Bar"; ctx.SaveChanges(); } }; public void Main(){ var foo = new Foo{Id=1,Bar="bar"}; Bar(foo); // Passes Bar(foo); // Throws exception } </code></pre> <p>If i check, if the entity is attached, or not, it returns false. (This seems normal to me, since the context was freshly created). Yet, when i try to attach it, it still throws the exception in this situation as well, yet, the context is new and the entity isn't attached.</p> <pre><code>public void Bar2(Foo foo){ using(var ctx = new MyContext()){ if(db.Entry(foo).State == EntityState.Detached) // Returns true!!! ctx.Foos.Attach(foo); // Executes this line as well, and still throws exception (after 2nd call) foo.Bar = "Bar2"; ctx.SaveChanges(); } }; public void Main2(){ var foo = new Foo{Id=2,Bar="bar2"}; Bar2(foo); // Passes Bar2(foo); // Throws exception } </code></pre> <p>How is this possible, and what can I do, to avoid it? Do I really have to Detach each and every poco that I'm attaching?</p> <p>UPDATE: The content of MyContext.cs:</p> <pre><code> public MyContext(): base("name=MyEntities") { ((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized += ObjectContext_OnObjectMaterialized; } protected override void Dispose(bool disposing) { ((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized -= ObjectContext_OnObjectMaterialized; base.Dispose(disposing); } private void ObjectContext_OnObjectMaterialized(object sender, ObjectMaterializedEventArgs e) { var entity = e.Entity as Model; if (entity == null) return; entity.Initialized(); } </code></pre>
 

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