title: Attaching an EF4 entity to a context more than one time
body: <p>So I'm working on an existing application that stores an entity in a Session variable and every postback attempts to re-attach it to a new context. I don't particularly care for this implementation, but re-writing it is out of the question for now. The code looks something like this:</p>
  
  <pre><code>public partial class ReviewDetail
  {
      DBContext context = new DBContext();
  
      public void Page_Load(object sender, EventArgs e)
      {
          if (!Page.IsPostBack)
          {
              int id = Convert.ToInt32(Request.QueryString["id"]);
              Session["Review"] = context.Reviews.FirstOrDefault(x =&gt; x.ReviewID = id);
          }
          else
          {
              Review review = Session["Review"] as Review;
              context.Attach(review);
          }
      }
  }
  </code></pre>
  
  <p><strong>This works on both initial page load and on the FIRST postback.</strong> However, on subsequent postbacks, it fails with the following error:</p>
  
  <p><em><strong>An object with a temporary EntityKey value cannot be attached to an object context.</em></strong></p>
  
  <p>The strange thing (to me, anyways) is that when I step through the code in the VS debugger and examine the properties of review.EntityKey, the IsTemporary field is false.</p>
  
  <p>Any suggestions on how I should approach a fix for this? I've tried calling .AttachTo("Reviews", review) but I end up with the same error. </p>
  
  <p>What I think I know so far is that when I make the first .Attach call, it attaches the "review" object, but since it's a reference object, it modifies the object in Session as well and adds an EntityKey to it (I may be incorrect on my terminology or my understanding here -- this is a little bit of a weak area in EF for me). So now, after the first postback, my Session object has been "attached". The second time around (when it fails), it's already been attached, so it's failing?</p>
  
  <p>I think I'm on the right track, just not sure how to approach a fix from here. Ideally, we wouldn't be doing it this way, but rewriting it to use a more correct approach probably isn't going to happen here unless there are no other alternatives.</p>
  
  <p>Any suggestions are appreciated.</p>
  
  <p><strong>EDIT:</strong> I should have mentioned this before someone answered with it, but I can't go back to the database on each postback to get the Review. The object in session is modified later on and it's data could be different from that of the data in the DB.</p>