title: How can I create a way for my repository to do an Upsert?
body: <p>I am using EF6.1.  I have a repository with these Insert and Update methods:</p>
  
  <pre><code>    public virtual void Insert(TEntity entity)
      {
          ((IObjectState) entity).ObjectState = ObjectState.Added;
          _dbSet.Attach(entity);
          _context.SyncObjectState(entity);
      }
      public virtual void Update(TEntity entity)
      {
          ((IObjectState) entity).ObjectState = ObjectState.Modified;
          _dbSet.Attach(entity);
          _context.SyncObjectState(entity);
      }
  </code></pre>
  
  <p>These are called from my controller with:</p>
  
  <pre><code>    public HttpResponseMessage Post(Exam exam)
      {
          try
          {
              _examService.Insert(exam);
              _unitOfWork.SaveChanges();
              return Request.CreateResponse&lt;Exam&gt;(HttpStatusCode.Created, exam);
          }
          catch (Exception ex)
          {
              return Request.CreateErrorResponse(HttpStatusCode.Conflict, ex);
          }
      }
  
      public HttpResponseMessage Put(int id, Exam exam)
      {
          if (id != exam.ExamId)
          {
              return Request.CreateResponse(HttpStatusCode.BadRequest);
          }
          try
          {
              _examService.Update(exam);
              _unitOfWork.SaveChanges();
              return Request.CreateResponse&lt;Exam&gt;(HttpStatusCode.OK, exam);
          }
          catch (DbUpdateConcurrencyException ex)
          {
              return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
          }
  
      }
  </code></pre>
  
  <p>and in my service layer:</p>
  
  <pre><code>    public virtual void Insert(TEntity entity)
      {
          _repository.Insert(entity);
      }
  
      public virtual void Update(TEntity entity)
      {
          _repository.Update(entity);
      }
  </code></pre>
  
  <p>I have a problem as there is a case where my application wants to do an update but there may be no object in the database to update. In this case I would like my code to do an insert instead. </p>
  
  <p>Is there a way this is normally handled with a repository pattern?  I read about Oracle and they have an upsert command.  However I am using SQL Server 2012 and a service layer and repository.  What would be a good way for me to do this? I would really like to have some way of trying an update and if it then fails doing an insert as 99% of the time the object will be present for me to update it.</p>