title: Delete entity if it exist, Add it if not exist in Entity Framework
body: <p>I want to remove entity from my context if it exist in database and if it is not exist, it's added to database.  </p>
  
  <p>How can I do this using <code>EntityState</code> in Entity Framework?  </p>
  
  <p>I want something like this:  </p>
  
  <pre><code>var fav = new ProductFavorite()
  {
      ProductId = productId,
      UserId = User.Identity.GetUserId()
  };
  
  if (_db.Entry(fav).State == EntityState.Detached)
  {
      _db.Entry(fav).State = EntityState.Added;
  }
  else
  {
      _db.Entry(fav).State = EntityState.Deleted;
  }
  
  _db.SaveChanges();
  </code></pre>
  
  <p>What is the best way for do this?</p>