2

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

1 Answer 1

2

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)");
}
Sign up to request clarification or add additional context in comments.

1 Comment

Then if it's not working how was it marked as correct answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.