0

I need to add unique constraint on column allowing null which can be achieved using the following query:

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

How can I achieve it using Entity Framework code first approach ?

4
  • 1
    There is Index attribute which could be applied to the property of the entity... But unfortunately, there is no Condition property for this attribute Commented Feb 22, 2018 at 14:23
  • Dupe of stackoverflow.com/questions/24361518/… Commented Feb 22, 2018 at 14:32
  • Possible duplicate of EF 6.1 Unique Nullable Index Commented Feb 22, 2018 at 14:32
  • @HemidAbbasov yea you are right I was required to add it using migration instead of using index attribute Commented Feb 22, 2018 at 16:06

1 Answer 1

1

You could use a migration to add the index:

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

2 Comments

Thanks for answering my question. I think also inside down() method I should add "drop index index_name" if I want to revert my migration
@SimpleCode yes you should add the drop index in the Down method

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.