Is it possible to express a check constraint?

后端 未结 2 1616
天涯浪人
天涯浪人 2020-12-10 14:53

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 ot

相关标签:
2条回答
  • 2020-12-10 15:25

    I've been wanting to put Check constraints in, and while there are a couple of ways to do it like the answer given here by M.Babcock and using the ExecuteSql in the Initializer to add constraints to the database manually.

    But I think the easiest method is to use a RegularExpression annotation, so in your example you'd go:

    public class Person
    {
        [Required]
        [RegularExpression(@"Bob|Harry")]  
        public string FirstName { get; set; }
    
        [Required, RegularExpression(@"5|30|50")]  
        public int Age { get; set; }
    }
    
    0 讨论(0)
  • 2020-12-10 15:38

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题