CheGuevarasBeret
CheGuevarasBeret

Reputation: 1414

check constraint entity framework

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?

Upvotes: 36

Views: 31838

Answers (2)

DharmaTurtle
DharmaTurtle

Reputation: 8447

EF Core 3

To take Ryan's example:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<SomeTable>(entity =>
        entity.HasCheckConstraint("CK_SomeTable_SomeColumn", "[SomeColumn] >= X");
}

Docs.


EF Core 7+

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder
        .Entity<Blog>()
        .ToTable(b => b.HasCheckConstraint("CK_Blog_TooFewBits", "Id > 1023"));
}

See EF Core breaking changes documenation for more details and changes in 7. Docs.

Upvotes: 41

David Sette
David Sette

Reputation: 753

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

Upvotes: 27

Related Questions