Add Constraint to Table column when using Create.Table, FluentMigrator
Asked Answered
T

2

20

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!

Tatiania answered 19/6, 2014 at 15:10 Comment(2)
E
26

This is a more idiomatic way of doing it in FluentMigrator

Create.UniqueConstraint("SalesIdAndUsername")
  .OnTable("users")
  .Columns("username", "SalesId");
Enid answered 7/4, 2015 at 8:41 Comment(3)
That's all well and good for a UNIQUE constraint, but the question is in regards to a CHECK constraint.Isocracy
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.Magnific
@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.Vevine
P
9

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)))");
Phraseologist answered 9/7, 2014 at 9:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.