title: How do I upsert a record in ADO.NET EF 4.1?
body: <p>I'm trying to accomplish something really simple and I can't find how to do it using Entity Framework 4.1.  </p>
  
  <p>I want a controller method that accepts an object and then does an UPSERT (either an insert or update depending on whether the record exists in the database).</p>
  
  <p>I am using a natural key, so there's no way for me to look at my POCO and tell if it's new or not.</p>
  
  <p>This is how I am doing it, and it seems wrong to me:</p>
  
  <pre><code>[HttpPost]
  public JsonResult SaveMyEntity(MyEntity entity)
  {            
      MyContainer db = new MyContainer(); // DbContext
      if (ModelState.IsValid)
      {
          var existing =
              db.MyEntitys.Find(entity.MyKey);
          if (existing == null)
          {
              db.MyEntitys.Add(entity);
          }
          else
          {
              existing.A = entity.A;
              existing.B = entity.B;
              db.Entry(existing).State = EntityState.Modified;
          }
          db.SaveChanges();
          return Json(new { Result = "Success" });
      }
  }
  </code></pre>
  
  <p>Ideally, the whole thing would just be something like this:</p>
  
  <pre><code>db.MyEntities.AddOrModify(entity);
  </code></pre>