【问题标题】:How to create conditional unique constraint using EF code first approach?如何使用 EF 代码优先方法创建条件唯一约束?
【发布时间】:2018-02-22 11:53:18
【问题描述】:

我需要在允许 null 的列上添加唯一约束,这可以使用以下查询来实现:

CREATE UNIQUE NONCLUSTERED INDEX idx_yourcolumn_notnull
ON YourTable(yourcolumn)
WHERE yourcolumn IS NOT NULL;

如何使用实体框架代码优先方法来实现它?

【问题讨论】:

标签: sql-server entity-framework ef-code-first data-annotations


【解决方案1】:

您可以使用迁移来添加索引:

public partial class CreateDatabase : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.Sql("CREATE UNIQUE NONCLUSTERED INDEX ourcolumn_notnull
ON YourTable(yourcolumn)
WHERE yourcolumn IS NOT NULL;");
    }
}

【讨论】:

  • 感谢您回答我的问题。我认为如果我想恢复我的迁移,我应该在 down() 方法中添加“drop index index_name”
  • @SimpleCode 是的,你应该在 Down 方法中添加下拉索引
猜你喜欢
  • 1970-01-01
  • 2014-03-28
  • 2017-05-05
  • 1970-01-01
  • 2018-09-06
  • 1970-01-01
  • 1970-01-01
  • 2019-06-12
  • 2012-11-15
相关资源
最近更新 更多