rtf_leg
rtf_leg

Reputation: 1819

Is it possible to add CHECK constraint with fluent API in EF7?

Is it possible to add CHECK constraint with fluent API in Entity Framework 7?

I need to acheive something like this:

...
ADD CONSTRAINT CK_SomeTable_SomeColumn CHECK (SomeColumn >= X);

It is ok if solution is provider-specific - I am targeting MsSqlServer only (at least now).

Upvotes: 20

Views: 11654

Answers (3)

Ryan Sparks
Ryan Sparks

Reputation: 1376

EF Core 7.0 +

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

EF Core 3.0 - 6.0

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

Upvotes: 23

Lukas Kabrt
Lukas Kabrt

Reputation: 5489

As of EF 7.0.0-rc1, it isn't possible with the fluent API.

You can define the constraint manually in the migration

migrationBuilder.Sql("ALTER TABLE SomeTable ADD CONSTRAINT CK_SomeTable_SomeColumn CHECK (SomeColumn >= X);");

Upvotes: 19

Alexei - check Codidact
Alexei - check Codidact

Reputation: 23078

Lukas Kabrt is still valid in 2019 so I had to create a special migration that I will include constraint and its drop:

        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql(@"
alter table AdminObjectReview add CONSTRAINT CK_AdminObjectReview_OnlyOneType CHECK 
( 
      (CASE WHEN AnswerId IS NULL THEN 0 ELSE 1 END)
    + (CASE WHEN QuestionId IS NULL THEN 0 ELSE 1 END)
    + (CASE WHEN CommentId IS NULL THEN 0 ELSE 1 END)
    + (CASE WHEN UserId IS NULL THEN 0 ELSE 1 END)
    + (CASE WHEN TagId IS NULL THEN 0 ELSE 1 END)
     = 1 )
");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql("alter table AdminObjectReview  drop CONSTRAINT CK_AdminObjectReview_OnlyOneType");
        }

Upvotes: 1

Related Questions