title: How to Check Unique Key Constraint
body: <p>I want check unique key constrain but I do not know which method to use.
  Which method is better?
  I use c#, EF, SQL Server</p>
  
  <p>First Method:</p>
  
  <pre><code>    bool contactExists = _db.Contacts.Any(contact =&gt; contact.ContactName.Equals(ContactName));
  
  if (contactExists)
  {
      return -1;
  }
  else
  {
      _db.Contacts.Add(myContact);
      _db.SaveChanges();
      return myContact.ContactID;
  }
  </code></pre>
  
  <p>Second Method:</p>
  
  <pre><code>Handle in exception.
  </code></pre>
  
  <p>The third method:
  check with T-SQL</p>
  
  <pre><code>If  Exists  (
      Select  Name
          From    dbo.ContentPage
          Where   Name    = RTRIM(LTRIM(N'page 1'))
      )
  </code></pre>
  
  <p>Begin
      Select  'True'
  End
  Else
  Begin
      Select  'False'
  End</p>