18

I am using FluentMigrator to create a new table in DB. After I created, i realized that I need to add a constraint like the following in T-Sql:

Assume I already have a table tableA

      Alter Table tableA
      Add Constraint ConstraintA CHECK(([ColA]>=(0) AND [ColA]<(100)))

How do I create the constraint using FluentMigrator in .Net? I have googled and did not find any answer. Thanks!

AlliceSmash
  • 687
  • 1
  • 11
  • 19
  • Much better answers here: [Is it possible to add CHECK constraint with fluent API in EF7?](https://stackoverflow.com/questions/34245449/is-it-possible-to-add-check-constraint-with-fluent-api-in-ef7) – AppFzx Jan 20 '22 at 04:19
  • And here: https://stackoverflow.com/a/34254423/1048432 https://stackoverflow.com/a/59895079/1048432 – AppFzx Jan 20 '22 at 04:20

2 Answers2

23

This is a more idiomatic way of doing it in FluentMigrator

Create.UniqueConstraint("SalesIdAndUsername")
  .OnTable("users")
  .Columns("username", "SalesId");
Karaaie
  • 527
  • 5
  • 15
  • 10
    That's all well and good for a UNIQUE constraint, but the question is in regards to a CHECK constraint. – Chad Gilbert Aug 04 '15 at 17:44
  • 2
    Even though it didn't address the original question directly, it was exactly what I was looking for (the question title does not discriminate about which type of constraint is wanted). I wish people would be more thoughtful about using the downvote option. A simple non-vote is way more appropriate in this case. – James Wilson Aug 02 '16 at 16:39
  • 2
    @JamesWilson well, I could also answer "42", and I can assure you that it's an answer to a very important question. Still, it doesn't answer to this. Just jocking, but I was trying to use this answer to create a `CHECK` constraint, which this answer does not provide. The other answer by Castrohenge is not pretty, but it's correct. – Alberto Chiesa Feb 21 '21 at 21:32
7

You could execute the raw SQL using the Execute.Sql method within your migration. Eg:

Execute.Sql("ALTER TABLE tableA ADD CONSTRAINT ConstraintA CHECK(([ColA]>=(0) AND [ColA]<(100)))");
Castrohenge
  • 8,525
  • 5
  • 39
  • 66