title: How can I create a generic UniqueValidationAttribute in C# and DataAnnotation?
body: <p>I'm trying to create a <code>UniqueAttribute</code> using the <code>System.ComponentModel.DataAnnotations.ValidationAttribute</code></p>
  
  <p>I want this to be generic as in I could pass the Linq DataContext, the table name, the field and validate if the incoming value is unique or not.</p>
  
  <p>Here is a non-compilable code fragment that I'm stuck at right now:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.ComponentModel.DataAnnotations;
  using System.Data.Linq;
  using System.ComponentModel;
  
  namespace LinkDev.Innovation.Miscellaneous.Validation.Attributes
  {
      public class UniqueAttribute : ValidationAttribute
      {
          public string Field { get; set; }
  
          public override bool IsValid(object value)
          {
              string str = (string)value;
              if (String.IsNullOrEmpty(str))
                  return true;
  
              // this is where I'm stuck
              return (!Table.Where(entity =&gt; entity.Field.Equals(str)).Any());           
          }
      }
  }
  </code></pre>
  
  <p>I should be using this in my model as follows:</p>
  
  <pre><code>[Required]
  [StringLength(10)]
  [Unique(new DataContext(),"Groups","name")]
  public string name { get; set; }
  </code></pre>
  
  <p>Edit:
  Note that according to this: <a href="https://stackoverflow.com/questions/294216/why-does-c-forbid-generic-attribute-types">Why does C# forbid generic attribute types?</a>
  I cannot use a generic type with the attribute.</p>
  
  <p>So my new approach here will be using Reflection/Expression trees to construct the Lambda expression tree on the fly.</p>