Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

IN EF can I add a check constraint so if my CustomerNotes entity has a boolean "FollowUpRequired" property I force user to enter a valid future date in the "FollowUpDate" property?

See Question&Answers more detail:os

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

1 Answer

EF does not support Check Constraints prior to EF Core 3.

That is, you cannot apply an attribute to an entity, and expect it to generate the appropriate SQL to create the Check constrint in the underlying database.

One way around this when using Code First Data Migrations (http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-code-based-migrations-walkthrough.aspx) is to generate a migration and add an Sql() line in the Up() function override that is generated

e.g.

public override void Up()
{
    // Auto generated code here
    // ...

    // YOUR CUSTOM SQL GOES HERE
    Sql("ALTER TABLE foo ADD CONSTRAINT CK_Some_Check CHECK (SomeDate > '20121110 00:00:00.000'");**
}

Also see this question and answer for some further information: Is it possible to express a check constraint?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...