title: How to check that the ID is not duplicated in ASP MVC and EF
body: <p>I am developing an <code>ASP .Net MVC 3</code>application using <code>C# and SQL Server 2005</code>.</p>
  
  <p>I am using also Entity Framework and Code First Method.</p>
  
  <p>I have a model <code>Poste</code> related to a table <code>Poste</code> in my base.</p>
  
  <p><strong>When I want to add a new poste, I would like that its ID 'Primary Key' will be checked in order to not be duplicate and produice an Exception.</strong></p>
  
  <p>I try to use <code>Remote</code> but there is some problems.</p>
  
  <p>This is what I try :</p>
  
  <p>Model :</p>
  
  <pre><code>public class Poste
      {
          [Required]
          [Key]
          [Display(Name = "ID Poste :")]
          [Remote("PosteExists", "Poste", "ID is already taken.")]
          public string ID_Poste { get; set; }
  </code></pre>
  
  <p>In the Controller 'PosteController' :</p>
  
  <pre><code>public JsonResult PosteExists(string poste)
          {
              var p = _repository.GetPosteByName(poste.Trim());
              return p == null ?
                  Json(true, JsonRequestBehavior.AllowGet) :
                  Json(string.Format("{0} is not available.", poste),
                      JsonRequestBehavior.AllowGet);
          }
  </code></pre>
  
  <p>First, <code>_repository</code> does not exist in the current Context.</p>
  
  <p>Second, I don't is this solution will be check the values from the base.</p>