title: Generic Way to Check If Entity Exists In Entity Framework?
body: <p>Similar to <a href="https://stackoverflow.com/questions/1802286/best-way-to-check-if-object-exists-in-entity-framework">Best way to check if object exists in Entity Framework?</a></p>
  
  <p>I'm looking for a generic way to check for an entity in a <code>DbSet</code>. Something like this, which doesn't work:</p>
  
  <pre><code>private DbContext DbContext { get; set; }
  
  private DbSet&lt;T&gt; DbSet { get; set; }
  
  public Boolean Exists(T entity) {
      return ((from item in this.DbSet
               where item == entity
               select item).Count() &gt; 0);
  }
  </code></pre>
  
  <p>The line <code>where item == entity</code> works in LINQ to SQL, but apparently not with LINQ to Entities. Since the entities may have different keys I can't have them all inherit from a common abstract with a known key for comparison.</p>
  
  <p><strike>I could do this, but I'm worried about the performance of catching exceptions as a verification process</strike> This doesn't work either since as long as the entity is detached the <code>OriginalValues</code> property can't be obtained:</p>
  
  <pre><code>public Boolean Exists(T entity) {
      try {
          var current = this.DbContext.Entry(entity).OriginalValues;
          // Won't reach this line if the entity isn't in the database yet
          return true;
      }
      catch (Exception ex) {
          return false;
      }
  }
  </code></pre>