title: The object is in a detached state. This operation cannot be performed on an ObjectStateEntry when the object is detached
body: <p>There's a pile of MVC/EF code that I am debugging that someone else has transliaterated-from-Java written.</p>
  
  <p>One snippet from the code resembles this:</p>
  
  <pre><code>public ActionResult Index()
      {
          using (var context = new Models.FooEntities())
          {
              var exp = context.Expenses.FirstOrDefault(e =&gt; e.Id == 17);
  
              if (exp != null)
              {
                  context.Expenses.DeleteObject(exp);
                  context.SaveChanges();
              }
          }
  
          return Content("Deleted");
      }
  </code></pre>
  
  <p>Simple. Right? It should delete the entity Expense with the ID 17.</p>
  
  <p>However, the call to <code>SaveChanges</code> raises an <code>InvalidOperationException</code> with the message, <code>"The object is in a detached state. This operation cannot be performed on an ObjectStateEntry when the object is detached."</code></p>
  
  <p>Now, I understand the message and I am surprised because the entity under question is never detached from the context. At least from what I see in the snippet above.</p>
  
  <p>There could be more than meets the eye, but I'll consider that as an option when I have no more choices because it's a nightmare to track the entire call-stack of this vasts piece of transliteration of mostly badly written Java code that no one understands.</p>