是否可以表达检查约束? [英] Is it possible to express a check constraint?
问题描述
我正在使用Entity Framework 4.3进行代码优先开发,似乎不可能表达一个 CHECK约束通过属性注释,或者任何其他方式。我看到EF 5.0将添加对检查枚举,但这不完全是我在这里之后。
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.
为了给出一个简化的例子,我想验证所有 Person
对象的名字为Bob或Harry,为5,10或30岁。
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; }
}
我可以运行一个alter script来添加这些约束,可以滚动自己的检查属性来执行验证,但是在实体框架中有没有实际表达非枚举的CHECK约束的方法?
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?
推荐答案
你可以自己写一个(未经测试):
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;
}
}
这篇关于是否可以表达检查约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!