title: Prevent duplicate insert without unique constraints using Entity Framework
body: <p>This is the classical "upsert" problem. I know how to achieve this using pure SQL, but wasn't able to find the equivalent using Entity Framework (v6, code first).</p>
  
  <p>Given the following entity:</p>
  
  <pre><code>public class Product
  {
      [Key]
      public int Id { get; set; }
  
      public string Sku { get; set; } // Should be unique
  
      // Other properties
  }
  </code></pre>
  
  <p>I want to create the Save(Product p) method which creates new record if the given Sku does not exist, or updates the existing record if that Sku already exist in the database. The Save method must not create records with duplicate Skus. Also, no unique constraints are defined on the Sku column in the DB. </p>
  
  <p>Checking for duplicates before inserting the record obviously won't work in multi-process environment. I tried wrapping the check in a transaction but that didn't work:</p>
  
  <pre><code>using (var db = new MyDbContext())
  using (var transaction = db.Database.BeginTransaction())
  {
      // if exists, retrieve and update
      // otherwise insert
  
      db.SaveChanges();
      transaction.Commit();
  }
  </code></pre>
  
  <p>Any clever ideas?</p>
  
  <p>Thanks!</p>