title: Efficiently Determine if EF 4 POCO Already in ObjectSet
body: <p>I'm trying EF 4 with POCO's on a small project for the first time.  In my Repository implementation, I want to provide a method AddOrUpdate that will add a passed-in POCO to the repository if it's new, else do nothing (as the updated POCO will be saved when SaveChanges is called).</p>
  
  <p>My first thought was to do this:</p>
  
  <pre><code>public void AddOrUpdate(Poco p)
  {
      if (!Ctx.Pocos.Contains&lt;Poco&gt;(p))
      {
          Ctx.Pocos.AddObject(p);
      }
  }
  </code></pre>
  
  <p>However that results in a <code>NotSupportedException</code> as documented under <a href="http://msdn.microsoft.com/en-us/library/bb896317.aspx" rel="nofollow noreferrer">Referencing Non-Scalar Variables Not Supported</a> (bonus question: why would that not be supported?)</p>
  
  <p>Just removing the <code>Contains</code> part and always calling AddObject results in an <code>InvalidStateException</code>:</p>
  
  <blockquote>
    <p>An object with the same key already
    exists in the ObjectStateManager. The
    existing object is in the Unchanged
    state. An object can only be added to
    the ObjectStateManager again if it is
    in the added state.</p>
  </blockquote>
  
  <p>So clearly EF 4 knows somewhere that this is a duplicate based on the key.</p>
  
  <p>What's a clean, efficient way for the Repository to update Pocos for either a new or pre-existing object when AddOrUpdate is called so that the subsequent call to SaveChanges() will do the right thing?</p>
  
  <p>I did consider carrying an isNew flag on the object itself, but I'm trying to take persistence ignorance as far as practical.</p>