title: ASP.NET MVC validation of uniqueness
body: <p>Rails has a very convenient uniqueness validation.</p>
  
  <p>ASP.NET MVC doesn't.</p>
  
  <p>I need to make sure that the e-mail address a user has entered hasn't been registered by anyone yet.</p>
  
  <p>I can see only one way of doing this kind of validation: create a new data context object in the UniqueAttribute class. </p>
  
  <p>But I'm afraid that wasting memory on a new data context object just for one validation is dangerous.</p>
  
  <p>Am I wrong? Is there a better way to do that?</p>
  
  <p><strong>Update</strong></p>
  
  <p>This is what I got so far</p>
  
  <pre><code>public class UniqueEmailAttribute : ValidationAttribute {
      public override bool IsValid(object value) {
          DataContext db = new DataContext();
          var userWithTheSameEmail = db.Users.SingleOrDefault(
              u =&gt; u.Email == (string)value);
          return userWithTheSameEmail == null;
      }
  }
  
  // Usage
  [UniqueEmail(ErrorMessage="This e-mail is already registered")]
  public string Email { get; set; }
  </code></pre>
  
  <p>There are two problems.</p>
  
  <ol>
  <li><p>It would be good to have just one UniqueAttribute class, not separate classes for e-mails, usernames etc. How can I do that?</p></li>
  <li><p>Creating a <strong>new</strong> data context every time you need to validate a single attribute.</p></li>
  </ol>
  
  <p><strong>SOLUTION</strong></p>
  
  <p>So in the end I created a unique constraint on the table and now I just have to intercept SqlException in Users repository. Works great and is probably more efficient than searching for the same node in the whole table. Thanks!</p>