views:

23

answers:

0

Hi,

In a MVC + ActiveRecord scenario, would it be possible/recommendable to validate db dependent properties as part of model binding? How would you go about implementing this - custom validation attribute?

A db dependent attribute could be active records ([Property(Unique=true)].

A simple example of its usage:

public class Person : ActiveRecordBase<Person>
{
   [Property(NotNull=true)]
   [Required]
   prop String Name;
   [Property(Unique=true,NotNull=true)]
   [Required]
   prop String SSN;
}

A Create action-method for a Person type could look something like this:

    [HttpPost]
    public ActionResult Create(Person newPerson)
    {
        if(ModelState.IsValid == false)
        {
            return PartialView("_Create", newPerson);
        }
        else
        {
            try
            {
                newPerson.Save();
            }
            catch (Exception e)
            {

            return PartialView("_Create", newPerson);
                //**Possible ActiveRecordException**
                throw;
            }
            return RedirectToAction("Index");
        }
    }

How would you recommend the possible unique constraint violations are added to modelstate?