user584018
user584018

Reputation: 11364

how to add min length check constraint in database side through EF code first?

I am trying to add check constraint in database side through Entity Framework code first approach,

ALTER TABLE [dbo].[YOUR_TABLE]
ADD CONSTRAINT [MinLengthConstraint] CHECK (DATALENGTH([your_column]) > 2)

I am decorating entity property with String Length & Min Length, but the check constraint is not applied to database table. Please suggest!

    [StringLength(100), MinLength(2)]
    public string StudentName { get; set; }  

Upvotes: 2

Views: 1412

Answers (1)

Ppp
Ppp

Reputation: 1015

How about this? Change StringLength to Maxlength.

[MaxLength(100), MinLength(2)]
public string StudentName { get; set; } 

Quite sure that it works with linq-to-entity but not sure if it will apply the constraint to DB level. Not working on DB level.

If you are using initializer, you can execute SqlCommand to create the constraint. A workaround for it. Not tested but should work.

protected override void Seed(MyContext context)
{
  context.Database.ExecuteSqlCommand("ALTER TABLE [dbo].[YOUR_TABLE]
  ADD CONSTRAINT [MinLengthConstraint] CHECK (DATALENGTH([your_column]) > 2)");
}

Upvotes: 2

Related Questions