Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...