Is it possible to express a check constraint?

谁都会走 提交于 2019-11-28 11:12:11

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;
    }
}
sh545

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; }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!