Search code examples
c#entity-frameworkentity-framework-4.3

Is it possible to express a check constraint?


I'm doing code-first development with Entity Framework 4.3 and it doesn't seem like it's possible to express a CHECK constraint via attribute annotations or, well, any other means. I see that EF 5.0 will be adding support for checking enumerations, but that's not exactly what I'm after here.

To give a simplified example, I'd like to validate that all Person objects have a first name of either "Bob" or "Harry" and are either 5, 10 or 30 years old.

public class Person
{
    [Required]
    [Check("Bob", "Harry")]  //yes, this attribute is imaginary
    public string FirstName { get; set; }

    [Required, Check(5, 30, 50)]  //check is still imaginary
    public int Age { get; set; }
}

I can run an alter script to add these constraints after the fact and I can roll my own check attribute to perform validations, but is there a way I'm missing to actually express non-enumerated CHECK constraints in Entity Framework?


Solution

  • You could write one yourself (untested):

    public class CheckAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
    {
        object[] ValidValues;
    
        public CheckAttribute<T>(params T[] validValues)
        {
            ValidValues = validValues;
        }
    
        public override bool IsValid(object value)
        {
            return ValidValues.FirstOrDefault(v => v.Equals(value)) != null;
        }
    }