title: Using MVC and fluent Nhibernate, how do I validate unique fields on my ViewModel before I bind them to my Domain Object and Save them?
body: <p>I have a website where I allow users to create new Part records.  I'm trying to figure out the best way to validate specific fields for uniqueness.  I want to make sure that somebody doesn't try to add a Part with PartNumber 1234 if that PartNumber already exists on a different Part.  </p>
  
  <p>The Web Application is using Asp.net MVC with fluent nHibernate for mapping my objects to the database.  I'm using Castle validation on my view models for things like ValidateNonEmpty, ValidateRange, etc.  Should I use the <a href="http://erichauser.net/2008/08/28/castle-validator-enhancements/" rel="nofollow noreferrer">ValidateSelf</a> method to query the repository to see if that part number already exists?  Something doesn't feel right about using my Repository on the ViewModel.  </p>
  
  <p>Would it be better for me to place that logic on the controller action?  That doesn't seem right because I expect my ViewModel to already be Validated at the point (during ModelBind).</p>
  
  <p>Or maybe its none of the above.  Thanks for any help on this one.</p>
  
  <p><strong>UPDATE</strong>
  Ok, not sure if this will help, but here is what my Save action looks like for a typical Create Action in my project:</p>
  
  <pre><code>public ActionResult Create(PartViewModel viewModel)
  {
   //I think I'd like to know if its Valid by this point, not on _repository.Save
   if(ModelState.IsValid)
   {
      try
      {
          var part = _partCreateViewModelMap.MapToEntity(viewModel);
  
          _repository.Save(part);
          return Redirect("~/Part/Details/" + part.Id);
      }
      catch (Exception e)
      {
          // skip on down...
      }
   }
  
   // return view to edit 
   return View(viewModel);
  }
  </code></pre>