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

孤街浪徒 提交于 2020-01-11 04:57:06

问题


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).


回答1:


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);");



回答2:


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


来源:https://stackoverflow.com/questions/34245449/is-it-possible-to-add-check-constraint-with-fluent-api-in-ef7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!