title: What is the simplest way to implement an Entity Framework 6 Add-or-Update method
body: <p>I have a project that uses Entity Framework 6 that does an Add-or-Update (i.e. Upsert) for a bunch of different entity types.  For each of these entities, there is an surrogate integer ID (i.e. primary key), a natural key (e.g. customer ID) used for external lookups, and a set of descriptive fields (e.g. Name, Description, etc.)  </p>
  
  <p>I have an AddOrUpdate method that does a lookup of the natural key, finds an existing entity in the database, and updates the entity with the new values (if it exists) or creates a new entity and adds it to the database (if it does not already exist).</p>
  
  <p>Here is a sample of the method I came up with (note that "key" is the natural key, not the surrogate ID):</p>
  
  <pre><code>public void AddOrUpdate(int key, string name)
  {
      var customer = _database.Customers
          .FirstOrDefault(p =&gt; p.Key == key);
  
      var exists = customer != null;
  
      if (!exists)
          customer = new Customer();
  
      customer.Name = name;
      // Update other descriptive fields here
  
      if (!exists)
          _database.Customers.Add(customer);
  
      _database.Save();
  }
  </code></pre>
  
  <p>The code works correctly, but it always feels a bit messy. I'm interested in knowing if someone has a better way of solving this problem with Entity Framework that is structurally simpler, reads better, or can be done in less lines of code (without sacrificing readability), and is still easy to unit test.</p>
  
  <p>If so, please post your refactoring of the code above, so that I can learn from your example.</p>